Allow @MockitoSettings to be inherited
See original GitHub issue- The mockito message in the stacktrace have useful information, but it didn’t help
- The problematic code (if that’s possible) is copied here; Note that some configuration are impossible to mock via Mockito
- Provide versions (mockito / jdk / os / any other relevant information)
- Provide a Short, Self Contained, Correct (Compilable), Example of the issue (same as any question on stackoverflow.com)
- Read the contributing guide
I have a base test class which among other things mocks a “serviceLocator” and a very common class used by many other services:
@ExtendWith(MockitoExtension.class)
public abstract class DomainServiceTests<T> {
@Mock
protected ServiceLocator sl;
@Spy
protected UserEnvironmentService userEnvironment;
@BeforeEach
public void setup() throws Exception {
Mockito.when(sl.get(UserEnvironmentService.class)).thenReturn(userEnvironment);
}
}
But whenever any test try to mock the get method of this serviceLocator with a different class I get an UnnecessaryStubbingException:
org.mockito.exceptions.misusing.UnnecessaryStubbingException:
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
1. -> at *.DomainServiceTests.setup(DomainServiceTests.java:24)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.
Then I specify the strictness in the base test class
@MockitoSettings(strictness = Strictness.WARN)
public abstract class DomainServiceTests<T> {
But even though the strictness is not seen by mockito.
I have debugged the code and found that the strictness is retrieved by searching the annotation on the method and the class of the test
This eventually calls
public static <A extends Annotation> Optional<A> findAnnotation(AnnotatedElement element, Class<A> annotationType) {
Preconditions.notNull(annotationType, "annotationType must not be null");
boolean inherited = annotationType.isAnnotationPresent(Inherited.class);
return findAnnotation(element, annotationType, inherited, new HashSet<>());
}
So if you annotate MockitoSettings
with java.lang.annotation.Inherited
it will work (I turned the inherited variable to true using the debugger to confirm).
For now I will have to annotate every test class with
@MockitoSettings(strictness = Strictness.WARN)
I am using Gradle 7.0 with JUnit 5.5.2
Thanks
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
That’s sadly a known issue with Maven Central, but the artifact should be installable for you: https://repo1.maven.org/maven2/org/mockito/mockito-core/3.3.0/
@TimvdLippe That’s awesome!
Unfortunately Travis is not very happy: