单元测试依赖方法 [英] Unit Test Dependent Methods

查看:90
本文介绍了单元测试依赖方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个测试项目,用于单元测试我的c#项目中的方法以及其中的各种测试方法。在实际方法中,使用全局类级别变量,其值从构造函数或其他方法设置。因此,当实际项目运行时,变量在方法中引用时具有值。现在,当我为测试方法运行测试时,它直接使用提供的参数调用实际方法,但是它不会获得全局变量的值,而是获得null。



所以我的问题是,是否可以对这种方法进行单元化,或者只对单独的方法进行单元测试?如果是,那怎么样?



提前谢谢。 :)

I have created a test project for unit testing the methods in my c# project and various test methods in it. In actual method, there are global class level variables used whose values are set from constructor or other methods. So when actual project runs, the variables have value when referenced in method. Now when I run test for test methods it directly calls the actual method with supplied parameters, but then it will not get the value of global variables, instead getting null.

So my question is that is it possible to unit such kind of methods, or only standalone methods can be unit tested? If yes, then how?

Thanks in advance. :)

推荐答案

这是一个经典案例。您可以在实现接口的config(或某个容器类)中创建全局因变量。现在在实例中使用config reader类实现你的接口,你的方法应该只从接口读取这些值。



你可以创建一个属性(或setter方法) )所以你可以注入一个测试实现



现在测试时你可以创建一个测试实现并用实现设置属性然后你的方法应该以相同的方式工作。



以下是一些示例代码:



This is a classic case. You can make the global dependent variables in a config (or some container class) which implements an interface. Now in the live example implement your interface with a config reader class and your methods should read these values from the interface only.

You can create a property (or setter method) so that you can inject a test implementation

Now while testing you can create a test implementation and set the property with the implementation and then your methods should work the same way.

Here is some example code:

public interface IPlayer
    {
        string Name { get; }
    }

public class Player : IPlayer // this class is your live class -- use a similar one in your test
{
     private InputManager inputManager;

     public Player(string name)
     {
         Name = name; // dependency inject or read from config
     }
}





如果您需要更多代码可以了解



let me know if you need more code to understand


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

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