我在spock中嘲笑一个类,只是想检查被测试方法中的方法是否被调用,我不想让内部方法运行。
class CalculationManager{
void processRequest(){
System.out.print("In process Request method") }
}
class CodeProcessor{
void processMessage(Request request){
CalculationManager calculationManager = new CalculationManager(request)
calculationManager.processRequest(request)
}
}
class Request{
int id
}
def "process code test"(){
given:
CodeProcessor codeProcessor = new CodeProcessor()
Request request = new Request()
request.setId(10)
CalculationManager calculationManager = Mock(CalculationManager)
when:
codeProcessor.processMessage(request)
then:
1 * calculationManager.processRequest()
}
在上面的例子中,我只需要检查是否正在调用encodeMessage。但是当我运行上面的代码时,它也会在encodeMessage()中运行代码。这不是预期的行为。任何人都可以指出我在哪里错了
答案 0 :(得分:0)
以下代码完美无缺,它失败了:
JUnit 4 Runner, Tests: 1, Failures: 1, Time: 86
Test Failure: process code test(Test)
Too few invocations for:
1 * codeProcessor.encodeMessage(request) (0 invocations)
Unmatched invocations (ordered by similarity):
1 * codeProcessor.processMessage(Request@20b56ae3)
代码:
@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')
import spock.lang.*
class Test extends Specification {
def "process code test"(){
given:
CodeProcessor codeProcessor = Mock(CodeProcessor)
Request request = new Request()
request.setId(10)
when:
codeProcessor.processMessage(request)
then:
1 * codeProcessor.encodeMessage(request)
}
}
class CodeProcessor {
void processMessage(Request request) {
encodeMessage(request)
}
void encodeMessage(Request request){}
}
class Request {
int id
}