问题
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