0

I simply try to test the following part of my service method:

if (isDeleted) {
    LoggingUtils.info("Deleted. ingredientUuuid: {}", ingredient.getUuid());
}

I try to use the following approach in order to catch the values passed to the static method:

// @RunWith(MockitoJUnitRunner.class)
@RunWith(PowerMockRunner.class)
public class DemoTest {

    @Test
    public void test() {

        // code omitted 

        Page<IngredientDTO> result = ingredientService.findAll(request,sort);

        PowerMockito.mockStatic(LoggingUtils.class);
        ArgumentCaptor<String> arg1 = ArgumentCaptor.forClass(String.class);
        ArgumentCaptor<UUID> arg2 = ArgumentCaptor.forClass(UUID.class);

        PowerMockito.verifyStatic(LoggingUtils.class, times(1));
        LoggingUtils.info(arg1.capture(), arg2.capture());


        // ...
    }
}

When debugging the test, it throws "The class com.company.common.LoggingUtils not prepared for test." pointing the following line:

PowerMockito.mockStatic(LoggingUtils.class);

So, how can I fix this problem?

  • Does anybody else have never used `PowerMockito`? –  Feb 09 '22 at 08:46
  • Does this answer your question? [Mock Static Methods in JUnit5 using PowerMockito](https://stackoverflow.com/questions/61975300/mock-static-methods-in-junit5-using-powermockito) – pringi Feb 09 '22 at 14:44
  • @pringi Thanks a lot for your help. I tried that approach but could not solve the problem. Maybe I do not apply the approach properly. I want to verify if the static method is called. This line: `LoggingUtils.info("Deleted. ingredientUuuid: {}", ingredient.getUuid());` In the documentation, there seems to be several examples for assertions I think, but when I try to use verify, it does not work. Any idea? –  Feb 10 '22 at 06:35
  • Do you need to use PowerMockito? Can't you use Mockito mock static instead? Example: https://www.baeldung.com/mockito-mock-static-methods. AFAIK PowerMockito development is stalled. Can be a incompatibility between java version and PowerMockito. – pringi Feb 10 '22 at 10:17
  • Thanks a lot, actually I do not have to use PowerMockito. But I already look at that page you suggested and it is not clear. What if I need to mock void with parameters and different options? And do I have to use try block? And good example do you suggest? –  Feb 11 '22 at 11:13
  • What about this question? https://stackoverflow.com/questions/71078892/unit-test-for-different-conditions-in-the-same-method –  Feb 11 '22 at 11:14

1 Answers1

0

Late answer, sorry for that, but maybe it still helps: Maybe you simply forgot the @PrepareForTest for your static class?

// @RunWith(MockitoJUnitRunner.class)
@RunWith(PowerMockRunner.class)
@PrepareForTest(LoggingUtils.class)  // <-- Required, otherwise you'll get exactly that "not prepared for test" error
public class DemoTest {
[...]
Nemax
  • 381
  • 2
  • 10