【发布时间】:2020-04-10 07:16:50
【问题描述】:
我正在尝试在 Spock 中模拟 org.springframework.web.client.RestOperations.exchange。
Spock 失败了
Too few invocations for:
1 * restOperations.exchange("https://test.com", HttpMethod.POST, _ as HttpEntity, String) (0 invocations)
Unmatched invocations (ordered by similarity):
1 * restOperations.exchange('https://test.com', POST, <whatever,[]>, class java.lang.String, [])
我认为问题与exchange 方法重载和我尝试调用的版本具有可变参数有关。
如何定义这种交互,以便测试成功?
MySubject.java:
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestOperations;
public class MySubject {
private final RestOperations rest;
public MySubject(RestOperations rest) {
this.rest = rest;
}
public void doStuff() {
HttpEntity<String> httpEntity = new HttpEntity<>("whatever");
rest.exchange("https://test.com", HttpMethod.POST, httpEntity);
}
}
MyTest.groovy:
import org.apache.http.HttpEntity
import org.springframework.http.HttpMethod
import org.springframework.web.client.RestOperations
import spock.lang.Specification
class MyTest extends Specification {
RestOperations restOperations = Mock(RestOperations)
MySubject subject = new MySubject(restOperations)
def "test"() {
when:
subject.doStuff()
then:
1 * restOperations.exchange("https://test.com", HttpMethod.POST, _ as HttpEntity, String)
}
}
【问题讨论】:
标签: spring-mvc mocking spock