我是 Java Spring boot 新手,并且创建了 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
}
关于java - 使用 Spring Boot RestController 进行 Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58905218/