是否可以对这种方法进行单元测试? [英] Is it possible to unit test this method?

查看:35
本文介绍了是否可以对这种方法进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下方法编写单元测试:

I have the following method for which I am trying to write a unit test:

using StaticClass;           // writen by some one else, have a dll

namespace Test
{
  Class TestClass
   {
      public void DoSomething(string param1)
      {
         List<string> = StaticClass.GetList(param1)

         // sort the list and do other studd here
      }
  }
}

当我不确定如何为 DoSomething 方法编写测试时,这取决于另一个类中的静态方法.该方法的输出取决于该机器上的数据库、环境和其他一些因素.所以如果两台机器上的数据库不同,同样的方法会得到不同的结果.我所知道的是 GetList 返回一些值,并且该方法可能已经或可能没有由该类的创建者进行单元测试.

When I am not sure how to write a test for the DoSomething method, that depends on a static method in another class. The output of that method depends on things like the database on that machine, the environment and few other other factors. So if databases on two machines are different, the same method would give different results. All I know is that GetList returns some value and that method may or maynot have been unit tested by the creator of that class.

我如何测试这样的方法?是否可以这样说,每当调用 StaticClass.Getlist 方法时,都会返回我在程序中创建的自定义 List ?我正在用 c# 编写测试.

How can I test such a method? Is it possible to say something like, whenever StaticClass.Getlist method is called return a custom List<String> that i created in my program? I am writing tests on c#.

谢谢,

推荐答案

带有副作用的方法的静态类型很麻烦.

Static types with methods that have side-effects are troublesome.

您有两个选择:

  • 短期:编写一个接口,该接口具有带有正确签名的 GetList 方法.接下来编写一个适配器——一个实现这个接口并在内部委托给 StaticClass 的类.将此适配器类型的实例作为 ctor arg 或方法 arg 传递到您的类中.调用 GetList 就可以了.您现在可以使用模拟框架创建模拟对象并将其传递到您的测试中并将其设置为返回预设值.
  • 长期:将 StaticClass 转换为非静态类.传入(而不是适配器对象);但这需要访问 StaticClass 的源代码.

这篇关于是否可以对这种方法进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆