I can't get Mockito to override a method in the class I am testing.
@Test
public void test_classToTest() throws Exception {
DependencyA dependencyA = mock(DependencyA.class);
DependencyB dependencyB = mock(DependencyB.class);
DependencyC dependencyC = mock(DependencyC.class);
ClassToTest classToTest = ClassToTest.builder().dependencyA(dependencyA)
.dependencyB(dependencyB).dependencyC(dependencyC).build();
classToTest= Mockito.spy(classToTest);
Mockito.doReturn("This is not the method you are looking for").when(classToTest).storeContent(null, null, null);
String result = classToTest.copyContent(someVariable, SOME_CONSTANT);
The method I am trying to override is classToTest.storeContent() which is called from inside classToTest.copyContent(). I am aware that this class is a little smelly, but I am not in a position to refactor it. However, this is not a very complicated setup and I am not sure why the actual .storeContent() method is getting called.
Instead of using the null
parameters to setup the mocked storeContent
method I would suggest using ArgumentMatchers.any
Eg
import static org.mockito.ArgumentMatchers.*;
// ...
Mockito.doReturn("This is not the method you are looking for").when(classToTest).storeContent(any(), any(), any());
There is a limitation in Mockito (and other mocking tools), that final
methods cannot be stubbed.
Maybe your ClassToTest#storeContent
is marked as final
?
If this is the case, just remove the final
keyword, and the stubbing mechanism should kick-in.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.