简体   繁体   中英

Java Unit test return the argument object

I have a test case which try to test whether the update of an object is successful.

The code trying to update is

@Override
public Company updateCompany(Long id, Company company) {

    Company existCompany = companyRepository.findOne(id);
    // doing something here to apply the values from company to existCompany

    return companyRepository.save(existCompany);
}

for the test case

@Test
public void testUpdateCompany() throws Exception {
    Company company = new Company("westpac", "www.westpac.com.au");
    Company existCompany = new Company("westpac", "www.westpac.com");

    when(companyRepository.findOne(anyLong())).thenReturn(existCompany);

    Company newCompany = companyService.updateCompany(1L, company);

    assertEquals(newCompany.getUrl(), "www.westpac.com.au");
}

becuase I did not mock the return value of companyRepository.save(existCompany); this will test failed.

My question here is:

Is there a way I can mock the return value exactly same as the args of the companyRepository.save(existCompany) ?

You can use Mockito.verify method to check the expected call to companyRepository.save method. Something like:

verify(companyRepository).save(existCompany);

In this case Company should have correct equals and hashCode methods

Another option is to use the ArgumentCaptor:

ArgumentCaptor<Company> argument = ArgumentCaptor.forClass(Company.class);
verify(companyRepository).save(argument.capture());
assertEquals(argument.getValue().getUrl(), --what you expect--);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM