如何使用help方法验证是否调用了即时字段的方法?

时间:2014-03-09 08:23:42

标签: spock

我的测试类是这样的:

public class HandlerTest extends Specification {
  Handler hander
  EventBus eventBus=Mock()     

  def setup(){
    handler=new Handler(eventBus)
  }

  def "test something"(){
     given:
     ....
     when:
     ....
     then://.....Here,I want to use help method 
      verifyBunchOfThingsHappenedOn()
  }

 def  verifyBunchOfThingsHappenedOn(){
    assert 1*eventBus.fireEvent(....)
    ......
 }
}

运行时,得到:

java.lang.NullPointerException
at com.test.HandlerTest.verifyBunchOfThingsHappenedOn(HandlerTest.groovy:194)
.......

我想也许即时字段引起了这个问题,所以试图传递局部变量来帮助方法,但得到了相同的结果:

   def "test something"(){
     given:
     ....
     when:
     ....
     then://.....Here,I want to use help method 
      verifyBunchOfThingsHappenedOn(eventBus)
  }

 def  verifyBunchOfThingsHappenedOn(EventBus eventBus){
    assert 1*eventBus.fireEvent(....)
    ......
 }

所以,问题是:

如何使用help方法验证是否调用了即时字段的方法?

1 个答案:

答案 0 :(得分:0)

您可以直接在Mock中添加默认互动,如here所述。

以下是一些功能齐全,可编译的源代码:

虚拟课程:

package de.scrum_master.app;

public class EventBus {
    public void fireEvent(String event) {
        System.out.println("Firing event: " + event);
    }
}
package de.scrum_master.app;

public class Handler {
    private EventBus eventBus;

    public Handler(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    public void handle(String event) {
        eventBus.fireEvent(event);
    }
}

Spock测试:

package de.scrum_master.app

import spock.lang.Specification

class HandlerTest extends Specification {
    Handler handler
    EventBus eventBus = Mock() {
        1 * fireEvent(_)
    }

    def setup(){
        handler = new Handler(eventBus)
    }

    def "test something"() {
        expect: handler.handle("My event")
    }

    def "test something else"() {
        expect: handler.handle("Another event")
    }
}