在 mockito 存根中传递实际参数



对于在实际生产代码中制作存根变量的情况,我们如何通过存根传递实际参数,例如在 JUnits 中使用 Mockito.when?

例如,如果生产代码中的方法如下所示:

1) servicaClass.doSomething(Calendar.getInstance)

2) servicaClass.doSomething(someMethodToCreateActualVariable())

在测试如何传递实际参数时?喜欢

-> when(mockedServiceClass.doSomething(Calendar.geInstance)).thenReturn("")

但是,在测试生产代码时,执行时将采用自己的日历值。

可以有

一种方法可以对要使用的变量进行公共 setter getter 方法的填充。但这似乎不是最佳解决方案。

这方面的任何指示会有所帮助吗?

如果您在事实之前知道匹配值,则可以使用存根。像 eq(与equals比较)和same(与==比较)这样的 mockito 匹配器将在那里提供帮助,或者您可以通过直接指定值来获取eq行为。请注意,如果您使用任何值,则必须对所有值使用匹配器;不能仅将匹配器用于双参数方法调用的一个参数。

// Without matchers
when(yourMock.method(objectToBeComparedWithEquals))
    .thenReturn(returnValue);
// With matchers
when(yourMock.method(eq(objectToBeComparedWithEquals)))
    .thenReturn(returnValue);
when(yourMock.method(same(objectToBeComparedReferentially)))
    .thenReturn(returnValue);

如果在运行该方法之前不知道匹配值,则可能需要改为进行验证。相同的规则适用于匹配器。

SomeValue someValue = yourSystemUnderTest.action();
verify(yourMock).initializeValue(someValue);

如果您需要在事后检查值,您可以使用 Captor:

ArgumentCaptor myCaptor = ArgumentCaptor.forClass(SomeValue.class);
yourSystemUnderTest.action();
verify(yourMock).initializeValue(myCaptor.capture());
SomeValue valueMockWasCalledWith = myCaptor.getValue();
// Now you've retrieved the reference out of the mock, so you can assert as usual.
assertEquals(42, valueMockWasCalledWith.getInteger());

最新更新