Unit Testing: Logging and Dependency Injection

后端 未结 9 692
臣服心动
臣服心动 2021-02-02 14:57

So regards logging from SO and other sites on the Internet the best response seems to be:

void DoSomething() {
    Logger.Log(\"Doing something!\");
    // Code.         


        
9条回答
  •  旧巷少年郎
    2021-02-02 15:47

    Most logging frameworks allow you to provide custom implementation for components. You can use that configuration mechanism to provide your own implementations.


    For instance, Java's Log4J allows you to declare custom appenders, which are the components responsible for 'delivering' a LoggingEvent.

    A logger can be easily mocked and injected using:

    Appender appenderMock = EasyMock.createMock(Appender.class);
    /* expect */ appenderMock.doAppend(EasyMock.isA(LoggingEvent.class));
    EasyMock.replay(appenderMock);
    
    Logger.getLogger(/* replace with your own */"My logger").addAppender(appenderMock);
    
    EasyMock.verify(appenderMock);
    

    This test only verifies that a logging event is sent, but you can refine it much more using EasyMock.

提交回复
热议问题