meta replacing same method in two different tests not working?

妖精的绣舞 提交于 2019-12-20 06:17:01

问题


Test controller is as follows

def justTest(){

    def res = paymentService.justTest()

    [status: res.status]

}

Test service method is as follows

def 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)

  }

Second test is as follows

    @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!


回答1:


I would take a different approach:

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

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

Or if you were using Spock instead of JUnit:

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


来源:https://stackoverflow.com/questions/55508397/meta-replacing-same-method-in-two-different-tests-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!