Ada*_*gen 0 java rest junit spring unit-testing
我有一个简单的 Java Spring REST API 应用程序,但我不知道如何对其进行单元测试。我已经阅读了 JUnit 和 Mockito 的文档,但我无法弄清楚。
这是 StudentController 类中的 post 方法
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void insertStudent(@RequestBody Student student){
studentService.insertStudent(student);
}
Run Code Online (Sandbox Code Playgroud)
这是 StudentService 类中的 insertStudent 方法
public void insertStudent(Student student) {
studentDao.insertStudent(student);
}
Run Code Online (Sandbox Code Playgroud)
我使用 MySQL 作为数据库。我也应该使用数据库进行单元测试吗?我的意思是我不想要任何集成测试。我只想要单元测试。我在 Node.js 中使用 supertest 并且它会照顾所有,我也可以用 JUnit 或 Mockito 做到这一点吗?
如果要进行单元测试,则不必连接到数据库。连接到数据库和其他外部服务将被视为集成测试。因此,在测试您的StudentService课程时会模拟对数据库的请求。
值得一提的第二点是,您将分别测试控制器类和服务类,但在您的情况下,这些测试看起来非常相似。
下面是一种可以测试控制器insertStrundent方法的方法。
@RunWith(MockitoJUnitRunner.class)
public class TestStudentContoller {
@Mock
StundentService mockStudentService;
@InjectMocks
StudentController studentController = new StudentController();
@Test
public void testInsertStudent(){
Student student = new Student();
studentContoller.insertStudent(student);
verify(studentService, times(1)).insertStudent(student);
}
Run Code Online (Sandbox Code Playgroud)
由于你的控制器的insertStudent方法没有if语句,只有一个分支,所以基本上只需要执行一个测试,基本上是控制器调用服务。
另一种测试方法是使用 Springs MockMvc。的好处MockMvc是它可以让您测试 HTTP 请求。例如,在这种情况下,您需要测试您的控制器insertStudent方法是否可以使用 JSON Student 正确响应 HTTP POST 请求。
@RunWith(MockitoJUnitRunner.class)
public class TestStudentContoller {
@Mock
StundentService mockStudentService;
@InjectMocks
StudentController studentController = new StudentController();
MockMvc mockMvc;
@Before
public void setup(){
mockMvc = MockMvcBuilders.standAloneSetup(studentController).build();
}
@Test
public void testInsertStudent(){
Student student = new Student();
studentContoller.insertStudent(student);
mockMvc.perform(post("path/to/insert/student")
.accept(MediaType.APPLICATION_JSON)
.andExpect(status().isOk())
.andExpect(content().string("{}"));//put json student in here
verify(studentService, times(1)).insertStudent(student);
}
Run Code Online (Sandbox Code Playgroud)
MockMvc 还有其他很酷的方法你应该探索。
| 归档时间: |
|
| 查看次数: |
10809 次 |
| 最近记录: |