bkoodaa
bkoodaa

Reputation: 5322

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?

Upvotes: 0

Views: 1708

Answers (2)

In order not to remove final, static fields/classes/methods in main java sources you could put mocks initialization after mockito's "when/then" stubs. It will call a constructor for the mock object with finals after all stubs initialization.

Try:

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

Upvotes: 0

Jeff Bowman
Jeff Bowman

Reputation: 95614

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.

Upvotes: 1

Related Questions