0

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?

occurred
  • 490
  • 1
  • 5
  • 13
  • Looking at your other Spock question, you seem to have a somewhat weird opinion about how to properly test your code. But anyway, if you are willing to provide an [MCVE](http://stackoverflow.com/help/mcve) as is good practice here on SO, I am willing to take a look at your problem. Probably others will, too. I would like to see **what** you want to test, not just **how** you assume you should go about it. – kriegaex Feb 22 '18 at 11:40

1 Answers1

0

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 e.g. 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.

jihor
  • 2,478
  • 14
  • 28