MockJS 是一個(gè)用于生成隨機(jī)數(shù)據(jù)和模擬 HTTP 請(qǐng)求的 JavaScript 庫,它可以用來優(yōu)化 Java 代碼,提高開發(fā)效率和測(cè)試覆蓋率。以下是如何借助 MockJS 優(yōu)化 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 {
// 模擬登錄接口返回的數(shù)據(jù)
when(loginService.login("username", "password")).thenReturn(new User("1", "username", "password"));
// 測(cè)試登錄接口
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 優(yōu)化 Java 代碼,提高開發(fā)效率和測(cè)試覆蓋率。