如何使用不实现equals的参数来模拟方法调用?
问题描述:
我正在为SystemLoggingService
编写单元测试,并嘲笑对其存储库的所有调用。 我使用Spring
与JPA
存储库。如何使用不实现equals的参数来模拟方法调用?
@Repository
public interface SystemLoggingRepository extends PagingAndSortingRepository<SystemLogEntity, Long>, JpaSpecificationExecutor<SystemLogEntity> {
}
对于服务方法findAll(Searchable searchable,Pageable pageable)
的一个单元测试我需要模拟存储库方法findAll(Specification<T> spec, Pageable pageable)
作为一个看到,所述Searchable
对象被变换到服务逻辑内的JPA Specifications
对象。
问题是我的服务逻辑将传递到存储库方法的JPA的Specifications
类不执行equals()
。
换句话说,我不能嘲笑库方法非常精确,因为我必须使用Matchers.any(Specifications.class)
BDDMockito.given(systemLoggingRepository.findAll(Matchers.any(Specifications.class), Matchers.eq(pageRequest))).willReturn(...)
如何不好是本作的单元测试的质量,或者这是常见的做法?对这个问题有什么不同的解决方法? Specifications
对象是一个Spring框架类。只是添加equals()
方法不是一个选项。
答
除的答案@VolodymyrPasechnyk你可能会想到将创建Specifications
对象的责任提取到一个单独的类,这将是另一个类依赖关系到您的CUT。
答
您可以尝试捕捉与规格:
ArgumentCaptor<Specifications> specificationsCaptor = ArgumentCaptor.forClass(Specifications.class);
BDDMockito.given(systemLoggingRepository.findAll(specificationsCaptor.capture(), Matchers.eq(pageRequest))).willReturn(...)
然后验证捕获值:
Specifications capturedSpecifications = specificationsCaptor.getValue();
assertThat(capturedSpecifications.getSomeProperty(), ...)
您可以在这里找到更多的信息:https://static.javadoc.io/org.mockito/mockito-core/2.8.47/org/mockito/Mockito.html#15
是的,这是一个想法。目前我不知道如何测试这个创建过程,但它标有一个问题。 –
@HerrDerb这是cleares的标志,应该移动到它自己的单位... –
是的,这是有道理的。如果我这样做的话,我也可以使用类匹配器Matchers.any(Specifications.class)来进行嘲讽而没有任何问题。我看到这个对吗? –