如何用Mockito测试控制器中的Delete方法



我不知道如何用Delete方法为我的控制器创建单元测试。

控制器类//

@PostMapping("delete")
public ResponseEntity<Void> deleteClient(@RequestBody DeleteClientModel deleteClientModel){
clientService.deleteClientById(deleteClientModel.getId());
return new ResponseEntity<>(HttpStatus.OK);
}

//服务类

public void deleteClientById(int id) {
clientRepository.deleteById(id);
}

正如你所看到的方法没有返回任何东西,所以这就是为什么我不知道如何测试控制器类。请帮帮我

这是一个测试

@Test
public void ClientController_deleteClient() throws Exception{
???
}

可以使用MockMvcRequestBuilder在springboot中运行控制器测试,如下所示

包含gradle依赖,testCompile('org.springframework.boot:spring-boot-starter-test')

@WebMvcTest(ClientController.class)
public class TestClientController {
@Autowired
private MockMvc mvc;
@Test
public void ClientController_deleteClient() throws Exception 
{
DeleteClientModel deleteClientModel = new DeleteClientModel();
deleteClientModel.setId("100");
mvc.perform( MockMvcRequestBuilders
.post("/delete")
.content(asJsonString(deleteClientModel))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
}
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

希望对你有所帮助:)

最新更新