本文介绍了如何在Groovy中使用Spock框架对日志记录错误进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


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






$ b

如何测试使用spock测试框架?

  class CarTest extends Specification {
deftest startCar(){
given :
Car newCar = new Car();

当:
newCar.startCar();

然后:
//如何提示消息已被记录?
}
}


解决方案

你可以检查记录器上的错误调用。

  @Grab(group ='org.spockframework',module ='spock-核心',版本='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扩展了spock.lang.Specification {

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



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


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???
    }
}
解决方案

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')
    }
}

这篇关于如何在Groovy中使用Spock框架对日志记录错误进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 18:29