I have the following controller:
@RestController
@RequestMapping("cats")
public class CatController {
private IDatabaseCatDao databaseCatService;
private DataValidator catDataValidator;
public CatController(IDatabaseCatDao databaseCatService, DataValidator catDataValidator) {
this.databaseCatService = databaseCatService;
this.catDataValidator = catDataValidator;
}
@PostMapping
public ResponseEntity addCat(@RequestBody Cat cat) {
catDataValidator.validateCatAdding(cat, cats);
databaseCatService.addCat(cat);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(cat.getName()).toUri();
return ResponseEntity.created(location).build();
}
}
catDataValidator - check if data is correct
databaseCatService - insert in database + caching locally
I need to test It using jUnit and Mockito.
My test class is following:
@RunWith(SpringRunner.class)
@WebMvcTest(value = CatController.class, secure = false)
public class CatControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private IDatabaseCatDao databaseCatService;
private String catExampleJson = "..some json file..";
public void addCat() throws Exception {
Mockito.doNothing().when(databaseCatService).addCat(Mockito.any(Cat.class));
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/cats")
.accept(MediaType.APPLICATION_JSON).content(catExampleJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
assertEquals(HttpStatus.CREATED.value(), response.getStatus());
}
}
Mockito.doNothing() because service addCat() is void method.
Validation I should better test separetely
Cats map I don't use here
java.lang.Exception: No runnable methods
update:
It can be something wrong with my dependencies, i am searching ..
Aucun commentaire:
Enregistrer un commentaire