Skip to content

Commit

Permalink
Fixes unchecked warnings when calling Mockito.mock(Class)
Browse files Browse the repository at this point in the history
This is an issue well known by the Mockito community, but prone to not
be fixed:
mockito/mockito#1531

Generics allow to ensure type-safety at compile time instead of runtime.
However, here it is used mainly to auto-cast the created object, thus
avoiding this burden on the developer. Indeed, it is in a context where
type safety is usually not a requirement, since the use of this method
is often the most trivial we can have: provide a class and expect a very
instance of this class in return.

This commit thus creates a less constrained mock method which builds on
Mockito's one, but without the constraint inducing this warning.
  • Loading branch information
matthieu-vergne committed May 5, 2024
1 parent 3d17d7f commit 8c6d25f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;

class GenericListVisitorAdapterTest {
Expand Down Expand Up @@ -2550,4 +2549,10 @@ void visit_CompactConstructorDeclaration () {
order.verifyNoMoreInteractions();
}

@SuppressWarnings("unchecked")
// Non type-safe mock method to avoid unchecked warnings
// Its use is trivial and systematic enough to not be a problem
private <T> T mock(Class<?> classToMock) {
return (T) Mockito.mock(classToMock);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;

public class GenericVisitorAdapterTest {
Expand Down Expand Up @@ -2549,4 +2548,10 @@ void visit_CompactConstructorDeclaration () {
order.verifyNoMoreInteractions();
}

@SuppressWarnings("unchecked")
// Non type-safe mock method to avoid unchecked warnings
// Its use is trivial and systematic enough to not be a problem
private <T> T mock(Class<?> classToMock) {
return (T) Mockito.mock(classToMock);
}
}

0 comments on commit 8c6d25f

Please sign in to comment.