Search code examples
springunit-testingtestingjunitmockito

Mockito when/then not working


I'm trying to Mock ValidatorService in unit tests of SubscriptionInterceptor.

validator = Mockito.mock(ValidatorService.class);
Mockito.when(validator.validateSubscription(any(), any(), any())).thenReturn("");
interceptor = new SubscriptionInterceptor(validator);

Later, when the interceptor calls the validateSubscription method of the mocked validator, an instance of the actual class is invoked, rather than the mock. Why? How can I get the method call to return an empty String?


Solution

  • Resolved in comments:

    Method was declared final.

    Mockito works by providing a proxy (subclass) of the class in question, with each of the methods overridden. However, for final classes and methods, Java assumes that it can detect which implementation it needs to call, and skips the dynamic method lookup. Because of this, Mockito cannot override behavior for final methods, static methods, or methods on final classes, and because you're not interacting with the mock Mockito cannot even warn you about it.

    This is a very common problem; be sure to check for final fields if Mockito is not working for stubbing/verifying your method.