2

In the TestNG unit test, I test, that an exception is caught and logged.

This code is being tested

    try {
        workloadServiceImpl.actionStarted(resourceType);
    } catch (Exception e) {
        LOGGER.error("Error measuring workload during actionStarted, resourceType=" + resourceType + ": " + e.getMessage(), e);
    }

by this test

@Test
public void testMeasureWorkflow_actionStartedExceptionCaught() throws Throwable {
    doThrow(new RuntimeException()).when(workloadService).actionStarted(any());
    tested.measureWorkloadForDatabase(joinPoint);
}

However during unit tests I don't want the exception to be logged. It catches other developers attention if they see it and then they waste time, by wondering, why is there an exception in log. Is there a mechanism, how to suppress logging of this exception during unit tests? We use logback, but logback-test.xml is being used also by integration tests and in that kind of test I don't want to suppress the exception logging, so fixing it in logback-test.xml file is not the preferred way.

Michal Krasny
  • 5,434
  • 7
  • 36
  • 64

2 Answers2

3

You'll want to create a filter that asserts the values of the logged event and doesn't allow the request to go through.

It is the same concept as what is done in How to verify that error was logged with unit tests but you'll have to port it to logback.

Community
  • 1
  • 1
jmehrens
  • 10,580
  • 1
  • 38
  • 47
0

I'm not familiar with logback, but can you turn off ERROR logging in testMeasureWorkflow_actionStartedExceptionCaught before you run it?

Brian Pipa
  • 808
  • 9
  • 23