【发布时间】:2019-04-10 14:51:51
【问题描述】:
我正在尝试使用 mockito 对 spring 控制器 进行测试,但它不起作用。
这是我的控制器:
@RestController
public class CandidateController {
private static final Logger log = LoggerFactory.getLogger(CandidateController.class);
private CandidateService candidateService;
@Autowired
public CandidateController(CandidateService candidateService) {
this.candidateService = candidateService;
}
@GetMapping("/candidates")
public ResponseEntity<List<Candidate>> getAllCandidates() {
List<Candidate> candidates = candidateService.findAll();
log.info("Candidates list size = {}", candidates.size());
if (candidates.size() == 0) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok(candidates);
}
@GetMapping("/candidates/{id}")
public ResponseEntity<Candidate> getCandidateById(@PathVariable int id) {
Candidate candidate = candidateService.findById(id);
if (candidate != null) {
return ResponseEntity.ok(candidate);
} else {
log.info("Candidate with id = {} not found", id);
return ResponseEntity.notFound().build();
}
}
@GetMapping("/candidates/name/{name}")
public ResponseEntity<List<Candidate>> getCandidatesWhereNameLike(@PathVariable String name) {
List<Candidate> candidates = candidateService.findByLastNameLike("%" + name + "%");
log.info("Candidates by name list size = {}", candidates.size());
if (candidates.isEmpty()) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok(candidates);
}
@PostMapping("/candidates/create")
public ResponseEntity<Object> postCandidate(@Valid @RequestBody Candidate candidate) {
Candidate newCandidate = candidateService.save(candidate);
if (newCandidate != null) {
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(newCandidate.getId())
.toUri();
return ResponseEntity.created(location).build();
} else {
log.info("Candidate is already existing or null");
return ResponseEntity.unprocessableEntity().build();
}
}
@PutMapping("/candidates/{id}")
public ResponseEntity<Object> updateCandidate(@PathVariable int id, @RequestBody Candidate candidate) {
candidateService.update(candidate, id);
candidate.setId(id);
return ResponseEntity.noContent().build();
}
@DeleteMapping("/candidates/{id}")
public ResponseEntity<Void> deleteCandidate(@PathVariable int id) {
candidateService.deleteById(id);
return ResponseEntity.noContent().build();
}
这是我的服务:
@Service
public class CandidateServiceImpl implements CandidateService {
private CandidateRepository candidateRepository;
private static final Logger log = LoggerFactory.getLogger(CandidateServiceImpl.class);
public CandidateServiceImpl() {
}
@Autowired
public CandidateServiceImpl(CandidateRepository repository) {
this.candidateRepository = repository;
}
@Override
public List<Candidate> findAll() {
List<Candidate> list = new ArrayList<>();
candidateRepository.findAll().forEach(e -> list.add(e));
return list;
}
@Override
public Candidate findById(int id) {
Candidate candidate = candidateRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(id));
return candidate;
}
@Override
public Candidate findBySocialNumber(int number) {
Candidate candidate = candidateRepository.findBySocialNumber(number).orElse(null);
return candidate;
}
@Override
public List<Candidate> findByLastNameLike(String userName) {
return candidateRepository.findByLastNameLike(userName).orElseThrow(() -> new ResourceNotFoundException(0, "No result matches candidates with name like : " + userName));
}
@Override
public Candidate save(Candidate candidate) {
Candidate duplicateCandidate = this.findBySocialNumber(candidate.getSocialNumber());
if (duplicateCandidate != null) { // Candidat existant avec numéro sécuAucun Candidat avec ce numéro sécu
log.info("Candidate with username = {} found in database", candidate.getSocialNumber());
throw new ResourceAlreadyExistException("Social security number : " + (candidate.getSocialNumber()));
}
log.info("Candidate with social number = {} found in database", candidate.getSocialNumber());
return candidateRepository.save(candidate);
}
@Override
public void update(Candidate candidate, int id) {
log.info("Candidate to be updated : id = {}", candidate.getId());
Candidate candidateFromDb = this.findById(id);
if (candidateFromDb != null) {
// Candidate présent => update
candidate.setId(id);
candidateRepository.save(candidate);
} else {
// Candidate absent => no update
log.info("Candidate with id = {} cannot found in the database", candidate.getId());
throw new ResourceNotFoundException(id);
}
}
@Override
public void deleteById(int id) {
Candidate candidate = this.findById(id);
if (candidate != null) {
candidateRepository.delete(candidate);
} else {
throw new ResourceNotFoundException(id);
}
}
}
我的测试文件:
@RunWith(SpringRunner.class)
@WebMvcTest(value = CandidateController.class, secure = false)
public class CandidateControllerTestMockito {
//parse date to use it in filling Candidate model
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateString = format.format(new Date());
Date date = format.parse("2009-12-31");
static private List<Candidate> candidates = new ArrayList<>();
static Candidate candidate = new Candidate();
{
candidate.setId(1);
candidate.setLastName("pierre");
candidate.setFirstName("pust");
candidate.setBirthDate(date);
candidate.setNationality("testFrancaise");
candidate.setBirthPlace("testParis");
candidate.setBirthDepartment("test92");
candidate.setGender("testMale");
candidate.setSocialNumber(1234);
candidate.setCategory("testCategory");
candidate.setStatus("testStatus");
candidate.setGrade("testGrade");
candidate.setFixedSalary(500);
candidate.setPrivatePhoneNumber(0707070707);
candidate.setPrivateEmail("test@ALEX.com");
candidate.setPosition("testPosition");
candidate.setStartingDate(date);
candidate.setSignatureDate(date);
candidate.setContractStatus("testContractStatus");
candidate.setContractEndDate("testContractEnd");
candidate.setIdBusinessManager(1);
candidate.setIdAdress(12);
candidate.setIdMissionOrder(11);
candidates.add(candidate);
}
@Autowired
private MockMvc mockMvc;
@MockBean
private CandidateService candidateService;
public CandidateControllerTestMockito() throws ParseException {
}
@Test
public void findAll() throws Exception {
when(
candidateService.findAll()).thenReturn(candidates);
RequestBuilder requestBuilder = get(
"/candidates").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println("ici"+candidates.toString());
String expected = "[{\"lastName\":\"pierre\",\"firstName\":\"pust\",\"birthDate\":1262214000000,\"nationality\":\"testFrancaise\",\"birthPlace\":\"testParis\",\"birthDepartment\":\"test92\",\"gender\":\"testMale\",\"socialNumber\":1234,\"category\":\"testCategory\",\"status\":\"testStatus\",\"grade\":\"testGrade\",\"fixedSalary\":500.0,\"privatePhoneNumber\":119304647,\"privateEmail\":\"test@ALEX.com\",\"position\":\"testPosition\",\"schoolYear\":null,\"startingDate\":1262214000000,\"signatureDate\":1262214000000,\"contractStatus\":\"testContractStatus\",\"contractEndDate\":\"testContractEnd\",\"idBusinessManager\":1,\"idAdress\":12,\"idMissionOrder\":11}]";
JSONAssert.assertEquals(expected, result.getResponse()
.getContentAsString(), false);
}
@Test
public void findByIdOk() throws Exception {
when(candidateService.findById(candidate.getId())).thenReturn(candidate);
Candidate cand=candidateService.findById(candidate.getId());
int idCand=cand.getId();
assertEquals(idCand,1);
RequestBuilder requestBuilder = get(
"/candidates/1").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void findByIdFail() throws Exception {
when(candidateService.findById(18)).thenReturn(null);
RequestBuilder requestBuilder = get(
"/candidates/18").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatus());
}
@Test
public void deleteCandidate() throws Exception{
when(candidateService.findById(candidate.getId())).thenReturn(candidate);
doNothing().when(candidateService).deleteById(candidate.getId());
mockMvc.perform(
delete("/candidates/{id}", candidate.getId()))
.andExpect(status().isNoContent());
}
我在问我是否以正确的方式做事? 我想为 deleteCandidateDontExist 做一个测试 我试过了:
when(candidateService.findById(candidate.getId())).thenReturn(null);
doNothing().when(candidateService).deleteById(candidate.getId());
mockMvc.perform(...
我期待未找到 404 的响应,但我收到 204 无内容的响应!
【问题讨论】:
标签: java spring rest spring-mvc mockito