gpt4 book ai didi

java - 类的模拟在 Spock 测试用例中不起作用

转载 作者:行者123 更新时间:2023-12-01 11:14:44 25 4
gpt4 key购买 nike

我正在尝试为 Rest Post 方法编写一个测试用例,该方法获取请求对象,转换为域对象并使用 spring jpa 存储库保存对象。

文件夹结构:

core.jar - 域、存储库和 daoscore.war - 服务、spock 测试、 Controller 。 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 中,任何人都可以帮助我解决这个问题吗?

谢谢

最佳答案

当您指定 saveDomain(domainObject) 时,您是在告诉 Spock 期望使用 domainObject 中的值来调用该方法作为范围。然而,在您的代码中,您将创建一个新的 DomainObject 并将传递给您的模拟。这就是我认为你想要的:

1 * domainDAO.saveDomain(_ as DomainObject) >> { it[0] }

关于java - 类的模拟在 Spock 测试用例中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31972795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com