简体   繁体   English

单元测试 - 如何在返回其他内容的方法中测试变量的内容?

[英]Unit Testing - How to test content of variable in a method that returns something else?

I have this pseudocode which I need to create Unit Test.我有这个伪代码,我需要创建单元测试。 How can I create unit test to verify content of x.name and x.type?如何创建单元测试来验证 x.name 和 x.type 的内容?

public async Task<T> functionA(Event eventData)
{
   var x = new ClassA();

   x.name = classB.name;
   x.type = classB.type;

  // Then adding x into a database

   return something like status.Success;
}

You don't actually want to test the value of x.name and x.type : those are implementation details.您实际上并不想测试x.namex.type的值:这些是实现细节。 What if you chose to use a different variable name, or avoid using a variable at all?如果您选择使用不同的变量名,或者完全避免使用变量怎么办? It would be a pain to have to update your unit test when you didn't actually change the externally-observable behavior of your method.当您实际上没有更改方法的外部可观察行为时,必须更新单元测试会很痛苦。

What you really want to test is whether this function adds the appropriate values to the database.您真正要测试的是此函数是否将适当的值添加到数据库中。 The ideal way to do this is to make sure that you're interacting with your database through a mockable dependency.执行此操作的理想方法是确保您通过可模拟的依赖项与数据库进行交互。 For example, if you have an IClassARepository interface that you provide to your class as a parameter to its constructor, then the "adding x into a database" code you omitted might look like this:例如,如果您有一个IClassARepository接口作为参数提供给类的构造函数,那么您省略的“将 x 添加到数据库”代码可能如下所示:

this.classARepository.Save(x);

Then you can use a library like Moq to create a Mock instance of that repository to inject in the instance of your class that you're unit testing, and after calling your method, you could verify that the values you want are passed into the Save method.然后,您可以使用像Moq这样的库来创建该存储库的 Mock 实例,以注入您正在单元测试的类的实例,在调用您的方法之后,您可以验证您想要的值是否传递到 Save方法。

repositoryMock.Verify(r => r.Save(It.Is((ClassA a) => a.name = "foo" && a.type == "bar")));

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

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