0

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!

kofhearts
  • 3,607
  • 8
  • 46
  • 79
  • I have not used JUnit but I would suggest to mock `PaymentService` instead of using `metaClass`. Also, try moving the following line as the first line of test `GroovySystem.metaClassRegistry.removeMetaClass(PaymentService.class)` – Puneet Behl Apr 04 '19 at 07:52

1 Answers1

0

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
}
sbglasius
  • 3,104
  • 20
  • 28