MockJS 是一個用于生成隨機數據和模擬 HTTP 請求的 JavaScript 庫,它可以用來優化 Java 代碼,提高開發效率和測試覆蓋率。以下是如何借助 MockJS 優化 Java 代碼的方法:
const Mock = require('mockjs')
const users = Mock.mock({
'list|10': [{
'id|+1': 1,
'name': '@name',
'age|20-50': 20,
'email': '@email'
}]
})
console.log(JSON.stringify(users.list, null, 2))
const Mock = require('mockjs')
Mock.mock('/api/login', 'post', {
'code|100-500': 100,
'message': '@string',
'data': {
'token': '@string'
}
})
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(controllers = LoginController.class)
public class LoginControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private LoginService loginService;
@Test
public void testLogin() throws Exception {
// 模擬登錄接口返回的數據
when(loginService.login("username", "password")).thenReturn(new User("1", "username", "password"));
// 測試登錄接口
mockMvc.perform(post("/api/login")
.param("username", "username")
.param("password", "password"))
.andExpect(status().isOk())
.andExpect(content().json("{\"code\":200,\"message\":\"success\",\"data\":{\"token\":\"123456\"}}"));
}
}
通過以上方法,你可以借助 MockJS 優化 Java 代碼,提高開發效率和測試覆蓋率。