0

My Class:

public class Util {
    private static final CustomLogger LOGGER = new CustomLogger(Util.class);

    public static void commitToDB() {
        try {
            CommitToDB();
        } catch (SQLException sqlException) {
             LOGGER.error("Exception in DB Commit", sqlException.getMessage(), sqlException);
        }
    }
}

My Unit Test Case Class:

@RunWith(PowerMockRunner.class)
@PrepareForTest({
        CustomLogger.class
})
public class UtilTest {
    @Mock
    private Util util;

    @Mock
    private CustomLogger CustomLogger;

    public void verifyFailedCommitRecords() throws SQLException {
        SQLException sqlException = new SQLException("Exception in DB Commit");
        doThrow(sqlException).when(protectedConn).commit();
        CustomLogger logger = PowerMockito.mock(CustomLogger.class);
        Util.CommitToDB();
        verify(logger, times(1)).error("Exception in DB Commit", sqlException.getMessage(), sqlException);
    }
}

I am getting error stating "Actually, there were zero interactions with this mock." Wanted but not invoked:

PS: Util.commitToDB calls an internal class protectedConnection which throws the SQLexception.

  • You mocked `Util`, so `Util.CommitToDB()` does nothing. – Lesiak Jan 05 '22 at 11:24
  • I have tried removing the Util mock too. Still I get the same error. I have also tried combination where Util and CustomLogger is mocked or not. All the combination gave same result. – Ramesh Gupta Jan 05 '22 at 12:13
  • You get same error, but the reason is different - you now enter `CommitToDB` while you haven't previously. Now your problem is equality of exceptions. – Lesiak Jan 05 '22 at 12:17
  • **Method threw 'org.mockito2.exceptions.base.MockitoException' exception. Cannot evaluate Util$MockitoMock$639069902.toString()** This exception message is availabel if I debug it via IDE. – Ramesh Gupta Jan 05 '22 at 12:18
  • @Lesiak I do enter the CommitToDB method. But I get the same exception each Time. When I debug via IDE the Logger line is definetly executed. – Ramesh Gupta Jan 05 '22 at 12:19
  • For debugger output - see https://stackoverflow.com/questions/69626405/mockito-unfinished-stubbing-exception-detected-only-in-intellij-debugger/69628236#69628236. For actual error - compare 2 instances of identical exceptions and think about consequences – Lesiak Jan 05 '22 at 12:29

1 Answers1

0

Adding the below line in the test method solve the problem:

 Whitebox.setInternalState(Util.class , "LOGGER" , logger);

After debugging , it appears that the Logger instance in the Util class and UtilTest class were different.

The reason mock was throwing an error "Wanted but not invoked" is because the logger instance invoking the method and the one used to verify in the unit test were different.