单元测试静态类 [英] UnitTesting Static Classes

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

问题描述

场景.C#语言,使用VS2008单元测试框架进行单元测试

Scenario. Language C#, Unit testing using VS2008 Unit testing framework

我有一个带有静态构造函数和2个方法的静态类.我编写了4种测试方法来测试整个类.我的静态构造函数有一些重要的初始化.

I have a static class with a static constructor and 2 methods. I have 4 test methods written to test the entire class. My Static Constructor has some important initializations.

现在,如果我同时运行所有4个单元测试用例,则静态构造函数将是仅在开始时调用.在每个测试用例的末尾,没有这样的东西

Now if I run all the 4 unit test cases in tandem, the static constructor will be called only at the beginning. At the end of each test case, there is no such thing

称为静态析构函数,因此构造函数中的状态信息将传递给下一个单元测试用例也.解决方法是什么?

called static destructor, So the state info in the constructor gets carried to the next unit test case also. What is the workaround for this.

推荐答案

最简单的解决方案是在静态类中添加重置"方法,该方法具有销毁和重建它的等效行为.

The simplest solution is to add a "Reset" method to your static class, which would have the equivalent behaviour of destructing it and reconstructing it.

在这里使用静态类可能有正当的理由.但是,由于静态方法在单元测试中不能很好地发挥作用,因此我通常会寻找替代设计.

There may be a valid reason why you are using a static class here. However, because statics don't play nicely with unit tests, I usually search for an alternative design.

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

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