【问题标题】:Mocking of class is not working in Spock Test case模拟类在 Spock 测试用例中不起作用
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多