【问题标题】:Understanding Grails mockFor demand了解 Grails mockFor 需求
【发布时间】:2014-04-25 19:54:36
【问题描述】:

我正在尝试为我的过滤器编写一个单元测试,并且我正在努力理解我的模拟对象的需求。这是一个简单的失败测试:

void "test my sanity"() {
    setup:
    def vendorPayment = mockFor(Payment)
    vendorPayment.demand.buyerId { -> 123}

    def vp = vendorPayment.createMock()
    //vp.buyerId=123
    println "buyer id: ${vp.buyerId}"

    when:
      def a = "testing"

    then:
      vp.buyerId == 123
}

我想模拟buyerId 的getter。使用需求不起作用,但如果我创建模拟然后设置买方 ID(注释行),测试将通过。需求不适用于吸气剂吗?是因为 getter 是隐式/动态创建的吗?

【问题讨论】:

    标签: unit-testing grails mocking


    【解决方案1】:

    必须模拟方法getBuyerId。 Groovy 在编译时为您添加了访问器方法,因此必须模拟按需方法。以这个简单的案例为例:

    class Payment {
        Integer buyerId
    }
    

    Payment.groovy 的 Getter/Setter 将在类编译后转换为字节码时添加。相应的测试如下所示:

    void "test my power"() {
        setup:
            def vendorPayment = mockFor(Payment)
            vendorPayment.demand.getBuyerId(1..2) { -> 123}
    
            def vp = vendorPayment.createMock()
            println "buyer id: ${vp.buyerId}"
    
        expect:
            vp.buyerId == 123
    
            //This would fail for < 2.3.* because of this bug which is fixed in 2.4
            //http://jira.grails.org/browse/GRAILS-11075
            vendorPayment.verify() //null
    
    }
    

    注意所做的更改:

    • getBuyerId 方法被模拟而不是字段 buyerId
    • 测试要求 getBuyerId 将被调用 1 到 2 次(第一次在打印时,第二次在阻塞中)。默认情况下,如果未指定任何内容,则假定该方法将被调用一次,在这种情况下会失败,因为getBuyerId 被调用了两次。
    • 我们还可以在测试完成后验证模拟控件是否正常工作

    【讨论】:

    • 这是否意味着我的模拟控制失败了?条件不满足:vendorPayment.verify() | | |空
    • 没有。 This is a bug 已在 2.4 中修复。
    • 很高兴知道。我们使用的是 2.3.7。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-02-27
    • 2018-10-29
    • 2010-11-15
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    相关资源
    最近更新 更多