Why is Mockito not returning my stubbed return values?

43 Views Asked by At

Craziest thing - I have a SpringMVC Junit-5 unit tester (with Mockito) configured as

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
@TestPropertySource("classpath:application-unit-test.properties)
public class MyTestClass {
 @Autowired MockMvc mockMvc;
 @SpyBean MyImpl myImpl;
 @MockBean MyBean aFewBeansLikeThis;

The controller relies heavily on our myImpl Spy, which also contains the method I am testing.

My Test has a bunch of doReturn statements then makes a mockMvc.perform(post()) call to the endpoint path, and everything is working perfectly, all tests passing, peace on earth.

But then here is the rub - I just extracted one method and made it public in myImpl1. Then I stub a proper response for that method, and lo and behold the tester insists on executing the real method on that SpyBean, even though I promise it is completely configured correctly to return the stub.

I tried using 2 of Mockito's returns syntaxes: doReturn(myObj).when(myImpl1).myMethod(); and when(myImpl1.myMethod()).thenReturn(myObj);

I put breakpoints in my code to ensure that the mocks and spy instances I am injected are actually the ones being used, and they definitely are

It is kind of frustrating, I recall this has happened to me in the past, usually rebuilding the project works, but this time nothing helps. All the other stub methods in that class work, just not the new one.

I really don't believe it is a syntax issue, so I won't complicate things with source code snippets; just asking in general would there be any reason that a stubbed method in a SpyBean would insist on calling the real method?

(Obviously the names have been changed to protect from the regulators)

1

There are 1 best solutions below

0
Victor Grazi On

I found the answer from the link in @Lunivore comment - when you are calling a method that expects parameters of type say String, then you must provide non-null values for those parameters. If you want to provide nulls, you have to provide the @nullable() argument type for those parameter positions