开发者

Disable logger during junit testing?

开发者 https://www.devze.com 2023-02-23 00:19 出处:网络
Is it possible to disable the execution of the logger during testing? I have this class public class UnitTestMe {

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.


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.


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.


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());


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消