1

我有一个关于单元测试的问题。

我将测试一个作为 Web 服务适配器的模块。测试的目的不是测试 Web 服务,而是测试适配器。

服务提供的一个函数调用如下:

class MyAdapterClass {

  WebService webservice;

  MyAdapterClass(WebService webservice) {
    this.webservice = webservice;
  }

  void myBusinessLogic() {
    List<VeryComplicatedClass> result = webservice.getResult();
    // <business logic here>
  }
}

如果我想对 myBusinessLogic 函数进行单元测试,通常的方法是注入一个模拟版本的 web服务,并getResult()为一些预定义的返回值设置函数。

但在这里我的问题是,真正的 web 服务将返回一个非常完整的类的列表,每个类都有数十个属性,并且该列表可能包含数百甚至数千个元素。

如果我要使用 Mockito 或类似的工具手动设置结果,这是一项巨大的工作。

在这种情况下,人们通常会做什么?我所做的只是连接到真正的 Web 服务并再次测试真正的服务。有什么好做的吗?

非常感谢。

4

2 回答 2

4

您可以编写代码来调用真正的 Web 服务,然后将其序列化为List<VeryComplicatedClass>磁盘上的文件,然后在设置中为您的模拟反序列化它并mockwebservice.getResult()返回该对象。这将节省您手动构建对象层次结构的时间。

更新:这基本上也是吉尔伯特在他的评论中建议的方法。


But really.. you don't want to set up a list of very completed classes each with tens of properties and the list could contain hundreds or even thousands of element, you want to setup a mock or a stub that captures the minimum necessary to write assertions around your business logic. That way the test better communicates the details that it actually cares about. More specifically, if the business logic calls 2 or 3 methods on VeryComplicatedClass then you want the test to be explicit that those are the conditions that are required for the things that the test asserts.

于 2012-04-18T19:33:56.243 回答
2

One thought I had reading the comments would be to introduce a new interface which can wrap List<VeryComplicatedClass> and make myBusinessLogic use that instead.

Then it is easy (/easier) to stub or mock an implementation of your new interface rather than deal with a very complicated class that you have little control over.

于 2012-04-18T21:20:07.810 回答