title: How to test Update method in Java Unit Test
body: <p>I am creating Unit Test for my ServiceImpl methods and I try to create a unit test for <code>update</code> method. However, I am not sure how should I test this method. It returns <code>DTO</code> of corresponding entity, but I have really no idea if I should use <code>@Spy</code> or <code>@Captor</code>. If I set a mock variable and then try to retrieve it and update its value, I will need to retrieve the same record to check its updated value.</p>
  <p>I am new in testing and I have not found a proper example for update method. Any help would be appreciated.</p>
  <pre><code>public CompanyDTO update(CompanyRequest companyRequest, UUID uuid) {
  
      final Company company = companyRepository.findByUuid(uuid)
              .orElseThrow(() -&gt; new EntityNotFoundException(COMPANY));
      company.setName(companyRequest.getName());
      final Company savedCompany = companyRepository.save(company);
      return new CompanyDTO(savedCompany);
  }
  </code></pre>
  <p><strong>Update:</strong> Finally I make it worked, but I am not sure for some parts. Is there anything missing or redundant in the following test method?</p>
  <pre><code>@InjectMocks
  private CompanyServiceImpl companyService;
  
  @Mock
  private CompanyRepository companyRepository;
  
  @Captor
  ArgumentCaptor&lt;Company&gt; companyCaptorEntity;    
  
  @Test
  public void testUpdate() {
      final UUID uuid = UUID.randomUUID();
      final CompanyRequest request = new CompanyRequest();
      request.setName(&quot;Updated Company Name&quot;);
  
      final Company company = new Company();
      company.setName(&quot;Company Name&quot;);
      
      when(companyRepository.findByUuid(uuid))
          .thenReturn(Optional.ofNullable(company));
  
      //??? Do we need this?
      when(companyRepository.save(any())).thenReturn(company);
  
      CompanyDTO result = companyService.update(request, uuid);
  
      Mockito.verify(companyRepository).save(companyCaptor.capture());
  
      Company savedCompany = companyCaptor.getValue();
      assertEquals(request.getName(), savedCompany.getName());
  }
  </code></pre>