经过少量修复的原始代码
所以首先我让m1 和m2 返回int 而不是void。然后至少你可以检查结果。然后我还确保在没有参数的情况下正确调用这些方法,正如 Chris 已经提到的那样。所以现在代码看起来像这样:
package de.scrum_master.stackoverflow.q62269054
import spock.lang.Specification
class MyTestSpec extends Specification {
def "testing addition using aMethod"() {
given:
Math math = new Math()
CalcIntf calcIntf = Mock(CalcIntf)
calcIntf.aMethod(_, _) >> { return 123 }
expect:
math.m1() == 123
}
def "testing addition using bMethod"() {
given:
Math math = new Math()
CalcIntf calcIntf = Mock(CalcIntf)
calcIntf.bMethod(_, _, _) >> { return 456 }
expect:
math.m2() == 456
}
interface CalcIntf {
int aMethod(int a, int b)
int bMethod(int a, int b, int c)
}
static class Calc implements CalcIntf {
int aMethod(int a, int b) {
return a + b
}
int bMethod(int a, int b, int c) {
return a + b + c
}
}
static class Math {
Calc calc = new Calc()
int m1() {
calc.aMethod(1, 2)
}
int m2() {
calc.bMethod(1, 2, 3)
}
}
}
当然,测试失败了:
Condition not satisfied:
math.m1() == 123
| | |
| 3 false
...
Condition not satisfied:
math.m2() == 456
| | |
| 6 false
...
失败的原因是你没有在任何地方注入你的模拟,但是Math通过Calc calc = new Calc()使用了一个硬编码的Calc实例。
使测试通过
所以我们需要一种注入模拟的方法,例如通过构造函数或设置器。您还应该将字段类型从Calc 更改为CalcIntf,否则无法注入接口模拟。如果您不在代码中使用接口而是针对具体子类编写代码,为什么还要创建接口?
package de.scrum_master.stackoverflow.q62269054
import spock.lang.Specification
class MyTestSpec extends Specification {
def "testing addition using aMethod"() {
given:
CalcIntf calcIntf = Mock(CalcIntf)
calcIntf.aMethod(_, _) >> { return 123 }
Math math = new Math(calcIntf)
expect:
math.m1() == 123
}
def "testing addition using bMethod"() {
given:
CalcIntf calcIntf = Mock(CalcIntf)
calcIntf.bMethod(_, _, _) >> { return 456 }
Math math = new Math(calcIntf)
expect:
math.m2() == 456
}
interface CalcIntf {
int aMethod(int a, int b)
int bMethod(int a, int b, int c)
}
static class Calc implements CalcIntf {
int aMethod(int a, int b) {
return a + b
}
int bMethod(int a, int b, int c) {
return a + b + c
}
}
static class Math {
CalcIntf calcIntf
Math(CalcIntf calcIntf) {
this.calcIntf = calcIntf
}
int m1() {
calcIntf.aMethod(1, 2)
}
int m2() {
calcIntf.bMethod(1, 2, 3)
}
}
}
您描述的测试行为
所以现在测试通过了,但它们没有重现您描述的行为:
对于其中一种方法,调用将转到真正的方法“bMethod()”,而不是返回的存根值。
我可以想象会发生这种情况的一个原因:您要存根的方法是final,这意味着实现模拟的动态代理无法覆盖它,因此不会存根它。但这与您在代码中描述的情况完全不同。
看到了吗?如果您的示例代码不能重现问题,那么它就完全没有用,这就是为什么在我的评论中我告诉您始终提供MCVE 而不是一些随机的伪代码。如果有人报告了您的代码中的错误,您也想知道如何重现它。
因此,为了重现您报告的问题,我必须做出有根据的猜测,因为您的代码没有帮助。只需在之前的版本中更改以下内容:
-
int bMethod(int a, int b, int c) → final int bMethod(int a, int b, int c)
-
Mock(CalcIntf) → Mock(Calc) 在两个地方
现在测试结果是:一种通过,一种失败的特征方法:
Condition not satisfied:
math.m2() == 456
| | |
| 6 false
...