我是Mockito的新手,我必须为我的REST控制器编写一个测试用例,但我不知道我应该从哪里开始。任何帮助都会非常感激。我已根据给定的建议更新了我的控制器。
这是我的控制器:
@RestController
@RequestMapping("/api")
public class TestController {
@Autowired
TestService _testService;
@RequestMapping(value = "/getsearchDetailCourse", method = RequestMethod.GET)
public List<TestDto> getsearchDetailCourse(@RequestParam("courseName") String courseName,
@RequestParam("courseId") Long courseId) throws Exception {
return (List<TestDto>) _testService.searchDetailCourse(courseName, courseId);
}
}
我的TestDto:
public class TestDto {
private String numberOfCourse;
private Long courseId;
public TestDto(){}
public TestDto(String numberOfCourse,Long courseId ){
super();
this.numberOfCourse = numberOfCourse;
this.courseId = courseId;
}
public String getNumberOfCourse() {
return numberOfCourse;
}
public void setNumberOfCourse(String numberOfCourse) {
this.numberOfCourse = numberOfCourse;
}
public Long getCourseId() {
return courseId;
}
public void setCourseId(Long courseId) {
this.courseId = courseId;
}
}
这是我的测试:
@RunWith(SpringRunner.class)
@WebMvcTest(value = TestController.class, secure = false)
public class TestMethod {
@Autowired
private MockMvc mockMvc;
@MockBean
private TestService testService;
TestDto testDto = new testDto("Test",2744L);
@Test
public void retrieveDetailsForCourse() throws Exception {
Mockito.when(
testService.searchDetailCourse(Mockito.anyString(),
,Mockito.anyLong())).thenReturn(testDto);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/api/getsearchDetailCourse").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println(result.getResponse());
String expected = "[{\"numberOfCourse\":\"Testing1\",\"courseId\":2744},{\"numberOfCourse\":\"Testing2\",\"courseId\":2744}]";
JSONAssert.assertEquals(expected, result.getResponse()
.getContentAsString(), false);
}
}
我想测试控制器,请帮我纠正上面的测试用例。