简体   繁体   中英

How to unit test logging error with Spock framework in groovy in a Spy-Class

I have a Class which has methods in it which I've to mock.

This is why I use Spy():

MyClass myClass = Spy(MyClass)

With following question: How to unit test logging error with Spock framework in groovy I could successfully get the logging message, but for this one, I'm not able to use just a normal instantiation of the class like:

MyClass myClass = new MyClass()

How is it possible to get the logging message in a Spock test, when the Class is a Spy?

A generic way to test logging is to write a simple appender which stores events in memory, set up the logging configuration to use it in tests, and then, after the tested code is run, get the logged events and verify them.

Assuming Logback is used, the test appender can be written eg like this:

public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
    private static final List<String> events = new ArrayList<>();

    public static synchronized List<String> getEvents() {
        return new ArrayList<>(events);
    }

    @Override
    protected void append(ILoggingEvent event) {
        synchronized(InMemoryAppender.class){
            events.add(event.getFormattedMessage());
        }
    }
}

I don't think the Spy has anything to help out with this, because it spies on the object's methods, not on its internal behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM