【问题标题】:Whats to best way to verify a void method is called in spock在 spock 中调用验证 void 方法的最佳方法是什么
【发布时间】:2021-01-02 15:09:40
【问题描述】:

假设我有一个类 Foo 有两个 void 方法 barbiz(Object object)

public class Foo {
  public void bar(){}
  public void biz(Object object){}
}

这两种方法都是具有自己测试用例的复杂方法,但问题是bar() 调用biz(Object object),我想在 bar 的一个测试用例中验证这一点。所以我的测试用例是在 Spock 中设置的。

class FooSpec {
  Foo foo = new Foo()
  
  def "test bar"() {
     given:
       boolean bizCalled = false
       foo.metaClass.biz = {Object object -> bizCalled = true}
     when:
       foo.bar()
     then:
       0 * _
     and:
       bizCalled
  }
}

我从this question 得到了这个解决方案,问题是在这个例子中bizCalled 总是假的,导致断言失败,即使我已经验证了biz(Object object) 所以bizCalled 应该设置为真。

我使用 metaClass 的方式是否有问题,或者在 spock 中是否有更正确的方法来验证 bar() 在 Spock 中调用 biz(Object object)

【问题讨论】:

    标签: unit-testing groovy spock


    【解决方案1】:

    你忘了让 FooSpec 扩展 Specification 以便真正让它成为一个 Spock 测试。如果你这样做,测试通过。这是您稍作调整和重命名的原始测试:

    public class Foo {
      public void bar() { biz("dummy"); }
      public void biz(Object object) {}
    }
    
    import spock.lang.Specification
    
    class InternalMethodCallTest extends Specification {
      Foo foo = new Foo()
    
      def "bar calls biz"() {
        given:
        boolean bizCalled = false
        foo.metaClass.biz = { Object object -> bizCalled = true }
    
        when:
        foo.bar()
    
        then:
        0 * _
    
        and:
        bizCalled
      }
    }
    

    但这不仅丑陋,而且“不令人毛骨悚然”。 ? 我建议您只需使用Spy 来验证内部方法调用:

    import spock.lang.Specification
    
    class InternalMethodCallTest extends Specification {
      Foo foo = Spy()
    
      def "bar calls biz"() {
        when:
        foo.bar()
    
        then:
        1 * foo.biz(_)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      • 2012-01-19
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多