5

Is it possible to disable the execution of the logger during testing?

I have this class

public class UnitTestMe {

    private final MockMe mockMe;
    private final SomethingElse something;

    private final Logger logger = LoggerFactory.getLogger(this.getClass().getClass());

    public UnitTestMe(MockMe mockMe, SomethingElse something) {
        this..
    }

    public toTest() {
        logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());
        mockMe.execute();
    }
}

My Unit Test is failing with an NullPointerException because something.foo() is not a mocked object (i am using mockito with nicemock).

How can I test this class without removing the logger statement and without mocking irrelevant parts of the dependencies like something?

Edit: something is in this case a Customer Object, that is not used in the toTest() function but needed in other parts of this Class. I am using the Customer class in the logger statement to relate an action to an user.

Edit 2: Would it help to mock the logger object? I would assume that I will get an NullPointerException again, because the methods of the `something´ object are executed, too.

2
  • can't you just surround it with try...catch (NullPointerException) ?
    – bluefoot
    Commented Apr 9, 2011 at 13:10
  • 3
    Never, ever, catch NullPointerException. Commented Apr 9, 2011 at 13:16

4 Answers 4

3

Poor answer: first decrease logging level to WARN or ERROR for this logger. Then, surround logging statement with isInfoEnabled():

if(logger.isInfoEnabled())
    logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());

Better one: it looks a bit weird that you are using some object only for logging, so when you are testing a toTest() method, mocked dependency is used only for logging. I understand this is just an example, but looks like there is some design flaw. I would suggest mocking SomethingElse for the sake of simplicity as well.

2

Your logging statement introduce an additional requirement for the mocking of something. You must make it give a non-null value returned for foo(), or rewrite your logging statements to avoid introducing these extra things.

1

You can suppress the execution of logger

usecase for PowerMockito:

// this is to suppress for logger.error(Exception e)
PowerMockito.doNothing().when(logger, "error", (Exception) any(Exception.class));

// this is to suppress for logger.debug(String message)
PowerMockito.doNothing().when(logger, "debug",anyString());
0

You can use try catch NullPointerException.

If your test method want to test NullPointerException it will be better us expect NullPointerException

@expect(NullPointerException.class)
public void testMethod() {
//your test method logic
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.