Reputation: 73
I have some integration tests that use Mockito, and they are working fine.
However, I want to verify that the input of a method that is called some time during the process I'm testing. The thing is: I don't want to mock the method behavior, only to inspect its argument and execute the real method. If I do something like this:
@MockBean
private ClassThatIsCalled classThatIsCalled;
@Captor
private ArgumentCaptor<TypeOfMyParameter> typeOfMyParameter;
I get an error because a dependency of ClassThatIsCalled
was not found. Even If I do given(classThatIsCalled.callMethod(any())).willCallRealMethod();
I'm still mocking ClassThatIsCalled
which is not what I want to do.
Is there a way to call the productive code of ClassThatIsCalled
(without mocking it) and simply inspect the passed argument?
TL;DR: I want to use @Spy
/@Captor
/similar to inspect an argument passed to a class, but without mocking the class, but calling its real method (using .willCallRealMethod()
is not enough, since a mocked class has no dependencies injected).
Upvotes: 0
Views: 830
Reputation: 265155
You should be able to use @SpyBean
:
Annotation that can be used to apply Mockito spies to a Spring
ApplicationContext
. Can be used as a class level annotation or on fields in either@Configuration
classes, or test classes that are@RunWith
the SpringRunner.Spies can be applied by type or by bean name. All beans in the context of a matching type (including subclasses) will be wrapped with the spy. If no existing bean is defined a new one will be added. Dependencies that are known to the application context but are not beans (such as those registered directly) will not be found and a spied bean will be added to the context alongside the existing dependency.
@ExtendWith(SpringExtension.class)
class YourTest {
@SpyBean
private ClassThatIsCalled classThatIsCalled;
@Captor
private ArgumentCaptor<TypeOfMyParameter> typeOfMyParameter;
// ...
}
Upvotes: 0