简体   繁体   English

如何获得用于单元测试的数据模板?

[英]How get data templates for unit tests?

I need to write a unit test for this method: 我需要为此方法编写一个单元测试:

public void MethodToTest(Data data)
{
     // ... some actions with data   
}

Data class: 资料类别:

public class Data
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Surname { get; set; }
    // ... hundred other properties
}

In my test I need some template object of Data type to manipulate it. 在我的测试中,我需要一些Data类型的模板对象来对其进行操作。 But this class has too many complex properties to write this "template" manually. 但是该类具有太多复杂的属性,无法手动编写此“模板”。 In real program Data objects are retrieved from DB. 在实际程序中, Data对象是从DB中检索的。 While debugging I can serialize some of them into XML or JSON. 在调试时,我可以将其中一些序列化为XML或JSON。 But then I need somehow deserialize it for test. 但是然后我需要以某种方式将其反序列化以进行测试。 Is believe there are a common patterns and tools to solve such issues. 相信存在解决此类问题的通用模式和工具。 So what is a proper way to do it? 那么什么是正确的方法呢?

If MethodToTest only uses a few parts of the Data class, you can define an interface that segregates those properties: 如果MethodToTest仅使用Data类的几个部分,则可以定义一个接口来分离这些属性:

public interface PersonalData {
  string Name {get; set; }
  int Age {get; set; }
  string Surname {get; set; }
}

public void MethodToTest (PersonalData data) { ... }

and have Data implement this interface 并让Data实现此接口

public class Data: PersonalData { ... }

Then you can use a test class that implements PersonalData for your test (or you might use a mocking framework to generate an implementation of PersonalData ). 然后,您可以使用为您的测试实现PersonalData的测试类(或者您可以使用模拟框架来生成PersonalData的实现)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM