MyService.class
public boolean myMethod1() {
boolean success = false
for (1..2) {
success = myMethod2()
}
return success
}
public boolean myMethod2() {
int value = otherService.someMethod() // mocked this method call
boolean saved = false
try {
// trying to persist value
} catch (ValidationException e) {
if (someCondition)
myMethod2() // comes back here instead of going to the method called : "Problem line"
}
return saved
}
我有一个测试用例,它模拟了
otherService.someMethod()
,每次执行都会返回不同的结果。使用groovy方式不会产生Grails错误-http://jira.grails.org/browse/GRAILS-4611
当存在验证异常并在特定条件下时,我想递归调用
myMethod2()
以获得用于保存数据的新输出。模拟方法闭包将以第一遍将返回int的方式返回输出,该int将在内部将(true / false)返回
myMethod1()
。下次(从循环开始)调用
otherService.someMethod()
时,它将返回输出,这将导致validationException
和它将为新输出调用相同的方法。现在,当第三次调用模拟方法时,
输出将返回一个不会引起validationException的不同值。执行try块后,
它涉及到
myMethod2()
的return语句,但它返回到“问题行”,而不是返回到myMethod1()
(调用它的那个)。如何使测试用例回调回
myMethod1()
最佳答案
这样想,我正在乘火车旅行,我从座位上站起来,通过一个互连从一个车厢走到另一个车厢,再到另一个车厢,再到另一个车厢。所以现在我在火车的第四厢。如果我想回到第一个车厢的座位,我必须从第4到第3到第2到第1一直走,因为我不能直接从第4车厢跳到第一个车厢(除非我是绿巨人或铁人人和在火车顶部)。相似的概念在方法调用中也很有用。method1()
调用method2()
调用method2()
调用method2()
。
而return
来自最后一个方法的值时,控件应以相反的顺序追溯。因此,为了返回到method1()
,您必须检查成功条件才能返回到调用者,如下所示:
public boolean myMethod2() {
int value = otherService.someMethod() // mocked this method call
boolean saved = false
try {
// trying to persist value
} catch (ValidationException e) {
if (someCondition){
myMethod2() // comes back here instead of going to the method called : "Problem line"
if(some value satisfied){
return // return to caller with true or false or whatever according to your need
}
}
}
return saved
}
关于grails - 递归方法在grails/groovy单元测试用例中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16240182/