How to unit test logging error with Spock structure 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 verify that an error has been logged using the spock testing platform?

 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??? } } 
+6
source share
1 answer

you can check for error in 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') } } 
+12
source

Source: https://habr.com/ru/post/971389/


All Articles