【发布时间】:2015-08-12 18:29:47
【问题描述】:
我正在尝试为 Rest Post 方法编写一个测试用例,该方法获取请求对象,转换为域对象并使用 spring jpa 存储库保存对象。
文件夹结构:
core.jar - 域、存储库和 daos core.war - 服务、spock 测试、控制器。 core.jar 是部分依赖jar
示例请求:
public class RequestObject {
private Long value2;
private Long value1;
... getters and setters
}
域对象
public class DomainObject {
private Object object1;
private Object object2;
private type field1;
private type field2;
private long version;
private date datecreated
... getters and setters
}
服务方式
@Autowired
DomainDAO domainDAO; // DomainDAO has domainRepository Autowired
@RequestMapping( value = "/domain", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE )
public DomainObject saveDomainObject(@RequestBody RequestObject request)
{
return domainDAO.saveDomain(buildDomainObject(request))
}
private DomainObject buildDomainObject(RequestObject request)
{
DomainObject object = new DomainObject()
object.setField1(request.getValue2());
etc ....
}
如果我使用 REST Client/SOAP/Swagger 到数据库,我将成功保存/更新。但是当我尝试用模拟编写 spock 测试用例时,我遇到了错误
测试用例
void "saveDomainObject success"() {
setup:
1 * domainDAO.saveDomain(domainObject) >> {DomainObject}
Gson gson = new Gson();
String json = gson.toJson(domainRequest);
when:
def resp = mockMvc.perform(post("/domain")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(json)).andReturn().response
def content = new JsonSlurper().parseText(resp.contentAsString)
then:
println content
}
错误信息
Too few invocations for:
1 * domainDAO.saveDomain(domainObject) >> {DomainObject} (0 invocations)
Unmatched invocations (ordered by similarity):
1 * domainDAO.saveDomain(com.test.core.domain.DomainObject@6f27c0ef)
at org.spockframework.mock.runtime.InteractionScope.verifyInteractions(InteractionScope.java:78)
at org.spockframework.mock.runtime.MockController.leaveScope(MockController.java:76)
at com.test.core.rest.service.DomainServiceServiceSpec.saveDomainObject success(DomainServiceSpec.groovy:132)
我在使用保存对象进行测试时遇到问题,我尝试了多个选项,但仍然遇到相同的错误。我怀疑这种情况正在发生,因为域对象在不同的 jar 中,有人可以帮我解决这个问题吗?
谢谢
【问题讨论】:
标签: java spring unit-testing spock