本文介绍了元在两个不同的测试中替换相同的方法不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试控制器如下

def justTest(){

    def res = paymentService.justTest()

    [status: res.status]

}

测试服务方法如下

def justTest(){



}

现在,这两个测试用例如下.在这两种情况下,都修改了付款服务方法justTest来返回两个不同的值.

Now the two test cases are as follows. Payment service method justTest was modified in both cases to return two different values.

    @Test
    void test1(){

        PaymentService.metaClass.justTest = {['status': true]}

        def res = controller.justTest()
        assertEquals(res.status, true)


        GroovySystem.metaClassRegistry.removeMetaClass(PaymentService.class)

  }

第二项测试如下

    @Test
    void test2(){

        PaymentService.metaClass.justTest = {['status': false]}

        def res = controller.justTest()
        assertEquals(res.status, false)


        GroovySystem.metaClassRegistry.removeMetaClass(PaymentService.class)

}

一个测试失败.当我使用调试器时,我注意到这种替换无法正常工作

One test is failing. When i used debugger, i noticed that this replacement is not working

PaymentService.metaClass.justTest = {['status': true]}

所以我想知道为什么一个元替换有效,而另一个则无效?使用元编程在两个不同的测试用例中不能更改相同的方法吗?感谢您的帮助.谢谢!

So i am wondering why one meta replacement is working and another not working? Is it not possible to change the same method in two different test cases using meta programming? I appreciate any help. Thanks!

推荐答案

我会采用其他方法:

void test1(){
    controller.paymentService = new PaymentService() {
        def justTest() {['status': true]}
    }

    def res = controller.justTest()
    assertEquals(res.status, true)
}

或者如果您使用的是Spock而不是JUnit:

Or if you were using Spock instead of JUnit:

void test1() {
    controller.parymentService = Stub() {
         justTest() >> [status: true]
    }
    // ...  other code
}

这篇关于元在两个不同的测试中替换相同的方法不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 23:22