[英]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);
因为我没有嘲笑companyRepository.save(existCompany);
的返回值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)
? 有没有一种方法可以模拟与companyRepository.save(existCompany)
的参数完全相同的返回值?
You can use Mockito.verify method to check the expected call to companyRepository.save method. 您可以使用Mockito.verify方法检查对companyRepository.save方法的预期调用。 Something like: 就像是:
verify(companyRepository).save(existCompany);
In this case Company should have correct equals and hashCode methods 在这种情况下,公司应具有正确的equals和hashCode方法
Another option is to use the ArgumentCaptor: 另一种选择是使用ArgumentCaptor:
ArgumentCaptor<Company> argument = ArgumentCaptor.forClass(Company.class);
verify(companyRepository).save(argument.capture());
assertEquals(argument.getValue().getUrl(), --what you expect--);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.