Mockito - 如果参数设置在另一个函数调用的函数中,如何进行单元测试
Mockito - how to unit test if argument is set in a function called by another function
我有两个类.
- Service.class
- Repository.class
我的 服务 正在调用 cleanup()
函数,然后从存储库 repository.insertSomething(something)
调用函数
我需要测试在 cleanup()
被调用后 insertSomething 是否设置为 属性。
我的测试代码是这样开始的
Service mock = mock(Service.class);
ArgumentCaptor<Repository> argument = ArgumentCaptor.forClass(Repository.class);
verify(mock).cleanup(); <-- have no access to the arguments of the child function and can't use the captor.
如示例中所示,我无法访问在清理函数范围内调用的函数。
我如何访问以测试被另一个函数调用的函数的参数。
PS.
我无法直接调用存储库函数,因为它从配置文件加载参数。鉴于 cleanup
函数已被调用,测试应该执行。
// Child method
@Query("insert into .... where ?1 < ....")
void insertSomething(LocalDate date);
您有一些服务想要测试。有一些内部依赖关系,您想检查它们的调用。
对于典型服务的单元测试,您通常应该像这样模拟所有内部依赖项及其行为:
class ServiceTest {
@Mock
private Repository repository;
@InjectMocks
private Service service;
@BeforeEach
void setUp(){
initMocks(this);
}
@Test
void serviseTest(){
SomeReturnType retVal = mock(SomeReturnType.class);
when(repository.call(any())).thenReturn(retVal);
service.call(any);
verify(repository).call(any());
verifyNoMoreInteractions(repository);
}
}
此泛型代码可以作为您问题解决方案的示例。
我有两个类.
- Service.class
- Repository.class
我的 服务 正在调用 cleanup()
函数,然后从存储库 repository.insertSomething(something)
我需要测试在 cleanup()
被调用后 insertSomething 是否设置为 属性。
我的测试代码是这样开始的
Service mock = mock(Service.class);
ArgumentCaptor<Repository> argument = ArgumentCaptor.forClass(Repository.class);
verify(mock).cleanup(); <-- have no access to the arguments of the child function and can't use the captor.
如示例中所示,我无法访问在清理函数范围内调用的函数。
我如何访问以测试被另一个函数调用的函数的参数。
PS.
我无法直接调用存储库函数,因为它从配置文件加载参数。鉴于 cleanup
函数已被调用,测试应该执行。
// Child method
@Query("insert into .... where ?1 < ....")
void insertSomething(LocalDate date);
您有一些服务想要测试。有一些内部依赖关系,您想检查它们的调用。 对于典型服务的单元测试,您通常应该像这样模拟所有内部依赖项及其行为:
class ServiceTest {
@Mock
private Repository repository;
@InjectMocks
private Service service;
@BeforeEach
void setUp(){
initMocks(this);
}
@Test
void serviseTest(){
SomeReturnType retVal = mock(SomeReturnType.class);
when(repository.call(any())).thenReturn(retVal);
service.call(any);
verify(repository).call(any());
verifyNoMoreInteractions(repository);
}
}
此泛型代码可以作为您问题解决方案的示例。