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.

1

There are 1 answers

1
Ramesh Gupta On

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.