如何使用Spock测试Logger的单个类?

时间:2014-07-03 17:50:04

标签: java logging groovy spock

所以我有一节课:

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

      public void someMethod() {
        logger.error("this is an error");
      }
}

ClassOneTest extends Specification {
    ExtractJustAddedObjectTypeIDsBolt bolt;

    void setup() { 
      this.bolt = new ExtractJustAddedObjectTypeIDsBolt();
    }

    void cleanup() { // run after every feature method

    }

    def "test someMethod"() {
      given:

      when:
      bolt.someMethod();

      then:
      bolt.logger.error("this is an error");
    }
}

但这是我得到的错误:

199  [main] ERROR member.bolt.ExtractJustAddedObjectTypeIDsBolt - this is an error

Too few invocations for:

1 * bolt.logger.error("this is an error")   (0 invocations)

Unmatched invocations (ordered by similarity):

1 个答案:

答案 0 :(得分:1)

尝试:

   def "test someMethod"() {
      given:
          def logger = Mock(Logger)
      and:
          bolt.logger = logger
      when:
          bolt.someMethod()
      then:
          1 * logger.error("this is an error")
    }

您需要首先模拟Logger。