title: Unit tests for Rest api controller
body: <p>I'm trying to do a test for a <em>spring controller</em> with <strong>mockito</strong> but it doesn't work.</p>
  
  <p>This is my controller :</p>
  
  <pre><code>@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&lt;List&lt;Candidate&gt;&gt; getAllCandidates() {
          List&lt;Candidate&gt; 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&lt;Candidate&gt; 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&lt;List&lt;Candidate&gt;&gt; getCandidatesWhereNameLike(@PathVariable String name) {
          List&lt;Candidate&gt; 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&lt;Object&gt; 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&lt;Object&gt; updateCandidate(@PathVariable int id, @RequestBody Candidate candidate) {
          candidateService.update(candidate, id);
          candidate.setId(id);
          return ResponseEntity.noContent().build();
      }
  
      @DeleteMapping("/candidates/{id}")
      public ResponseEntity&lt;Void&gt; deleteCandidate(@PathVariable int id) {
          candidateService.deleteById(id);
          return ResponseEntity.noContent().build();
      }
  
  </code></pre>
  
  <p>This is my Service: </p>
  
  <pre><code>
  @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&lt;Candidate&gt; findAll() {
          List&lt;Candidate&gt; list = new ArrayList&lt;&gt;();
          candidateRepository.findAll().forEach(e -&gt; list.add(e));
          return list;
      }
  
      @Override
      public Candidate findById(int id) {
          Candidate candidate = candidateRepository.findById(id).orElseThrow(() -&gt; new ResourceNotFoundException(id));
          return candidate;
      }
  
      @Override
      public Candidate findBySocialNumber(int number) {
          Candidate candidate = candidateRepository.findBySocialNumber(number).orElse(null);
          return candidate;
      }
  
      @Override
      public List&lt;Candidate&gt; findByLastNameLike(String userName) {
          return candidateRepository.findByLastNameLike(userName).orElseThrow(() -&gt; 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 =&gt; update
              candidate.setId(id);
              candidateRepository.save(candidate);
          } else {
              // Candidate absent =&gt; 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);
          }
      }
  }
  
  </code></pre>
  
  <p>My test File:</p>
  
  <pre><code>@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&lt;Candidate&gt; candidates = new ArrayList&lt;&gt;();
  
  
      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());
  
      }
  
  
  
  </code></pre>
  
  <p>am asking if i'm doing in the right way or no ? 
  and i want to do a TEST for deleteCandidateDontExist 
  i tried : </p>
  
  <pre><code>when(candidateService.findById(candidate.getId())).thenReturn(null);
          doNothing().when(candidateService).deleteById(candidate.getId());
   mockMvc.perform(...
  
  
  </code></pre>
  
  <p>Am expecting a response with <strong>404</strong> not found but I get a response with <strong>204</strong> no content!</p>