[英]Junit testing with spring boot restcontroller
我是 Java Spring 启动的新手,并创建了一个 Restcontroller、存储库和服务层。 现在我正在尝试使用 junit 和 mockito 测试 restcontroller,我应该如何解决这个问题?
@RequestMapping("/Heise")
@RestController
private HeiseService heiseService;
public HeiseController(HeiseService heiseService) {
this.heiseService = heiseService;
}
// return the whole heise data
@RequestMapping(value = "/all", method = RequestMethod.GET)
public List<Heise> getAllHeise(){
return heiseService.getAllHeise();
}
// return specific data with given id
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Optional<Heise> getHeiseById(@PathVariable("id") String id){
return heiseService.getHeiseById(id);
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public void createHeise(@Valid @RequestBody Heise heise){
heiseService.save(heise);
};
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
public void deleteHeiseData (@PathVariable String id){
heiseService.deleteById(id);
}
@RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
public void updateHeiseCollectionByID(@PathVariable("id") String id, @Valid @RequestBody Heise heise ) {
heiseService.save(heise);
}
}
您应该在 Controller 层模拟服务器层以实现单元测试。 另外,您可以使用 WebMvcTest 配置来模拟您的 Http 服务器。
例如:
@RunWith(SpringRunner.class) // To mock Service Layer
@WebMvcTest(controllers = HeiseController.class) // To mock Your Http Server
public class HeiseControllerTest{
@Autowired
private MockMvc heiseRestController; // it will be injected by WebMvcTest context loader
@MockBean
private HeiseService heiseService; // the mock service
@Test
public void testGetPresentHeiseById(){
// Mock the getById method of heiseService
Heise heise = new Heise(3); // heise having id = 3
Mockito.when(heiseService.getById(3)).thenReturn(Optional.of(heise));
// Build the request method = GET
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/heise", 3); // with id url path = 3
// Http Response Checking
ResultMatcher expextedStatus = MockMvcResultMatchers.status().is(HttpStatus.OK.value()); // status = 200
// Controller Test
heiseController.perform(requestBuilder).andExpect(expectedStatus);
// to test the body of response, you may learn about ModelMapper
}
// your unit tests
// @see RequestBuilder to build Http Request
// @see ResultMatcher to test Http Response
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.