Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test logging error with Spock framework in groovy

So I have a class that has a method that logs a message:

class Car {
    private Logger logger = LoggerFactory.getLogger(Car.class);


    void startCar() {
        logger.error("car stopped working");
    }
}

How can I test that the error was logged using the spock testing framework?

class CarTest extends Specification {
    def "test startCar"() {
        given:
        Car newCar = new Car();

        when:
        newCar.startCar();

        then:
        // HOW CAN I ASSERT THAT THE MESSAGE WAS LOGGED???
    }
}
like image 480
Wang-Zhao-Liu Q Avatar asked Jun 26 '14 19:06

Wang-Zhao-Liu Q


2 Answers

you could check for an invocation of error on the logger

@Grab(group='org.spockframework', module='spock-core', version='0.7-groovy-2.0')
@Grab(group='org.slf4j', module='slf4j-api', version='1.7.7')
@Grab(group='ch.qos.logback', module='logback-classic', version='1.1.2')

import org.slf4j.Logger

class MockLog extends spock.lang.Specification {

    public class Car {
        private Logger logger = org.slf4j.LoggerFactory.getLogger(Car.class);
        void startCar() {
            logger.error('car stopped working');
        }
    }

    def "mock log"() {
    given:
        def car = new Car()
        car.logger = Mock(Logger)
    when:
        car.startCar()
    then:
        1 * car.logger.error('car stopped working')
    }
}

edit: Full example https://github.com/christoph-frick/spock-test-logging

like image 187
cfrick Avatar answered Oct 03 '22 17:10

cfrick


My Loggers are private static final so I cannot use solution mentioned above and rather not use Reflection.

If you are using Spring, you have acces to OutputCaptureRule.

@Rule
OutputCaptureRule outputCaptureRule = new OutputCaptureRule()

def test(){
outputCaptureRule.getAll().contains("<your test output>")
}
like image 20
Sven Dhaens Avatar answered Oct 03 '22 15:10

Sven Dhaens