I have a Component
class called AppUtil
with a bunch of public
static
methods:
@Component
public class AppUtil {
// Methods, fields...
public static List<String> getActiveProfiles() {
return newArrayList(appUtil.env.getActiveProfiles());
}
public static String readResourceFileAsString(String fileName) throws IOException {
return IOUtils.toString(new FileReader(fileName));
}
// More methods....
}
The two static
methods writen above are called by a method called loadUserByUsername
of a class called GearApiUserDetailsService
. In order to test GearApiUserDetailsService.loadUserByUsername
, I want to mock the calls to these static
methods of AppUtil
. This is what my unit testing class looks like right now:
@RunWith(MockitoJUnitRunner.class)
public class GearApiUserDetailsServiceTest {
@InjectMocks
private GearApiUserDetailsService gearApiUserDetailsService;
@Before
public void setUp(){
MockitoAnnotations.openMocks(this);
}
@Test
public void testLoadUserByUsernameWithoutActiveProfiles(){
try (MockedStatic<AppUtil> mockedStatic = Mockito.mockStatic(AppUtil.class)) {
mockedStatic.when(AppUtil::getActiveProfiles).thenReturn(Collections.emptyList());
mockedStatic.when(AppUtil::readResourceFileAsString).thenReturn("random string");
final String apiKey = "someExampleAPIKey";
UserDetails userDetails = gearApiUserDetailsService.loadUserByUsername(apiKey);
assertEquals(apiKey, userDetails.getUsername());
}
}
}
The problem is that while the mock of getActiveProfiles
works well (tested), the mock of readResourceFileAsString
fails at compile time even, with IntelliJ reporting that it can't resolve it:
The methods are both public
and static
, with the only difference being that the second one takes an argument.
This 2020 post seems to suggest ensuring that the pom
file contains a dependency of mockito-core
at version 3.5.13
. I have included this dependency, invalidated caches / restarted, tried to re-run entire maven build lifecycle, but obviously it still fails at compile time because of the aforementioned error. Ideas? (=
I was able to determine, through a very recent Baeldung entry, that when one mocks static methods with arguments, one has to use an instance of the functional interface
MockedStatic.Verification
, which can be the target of a lambda expression. So, changing this:to:
did the trick. Marking this answer accepted after necessary 24 hour period.