我有一个公共(public)静态类,我正在尝试使用 Visual Studio 2012 的内置测试框架进行单元测试。当我尝试对其运行单元测试时出现此错误:
The type initializer for 'Foo.Bar.Controllers.DataService' threw an exception.
内部异常说:
{"Value cannot be null.\r\nParameter name: value"}
at System.Boolean.Parse(String value)
我要测试的类是:
命名空间 Foo.Bar.Controllers {
public static class DataService {
private static ClassINeedOneInstanceOf _dataGettingClass = new ClassINeedOneInstanceOf();
public static List<Info> GetServiceInfoList(String svcName) {
List<Info> infoList = null;
if (ERROR CHECKING AND STUFF) {
infoList = _dataGettingClass.GetInfoFromAwesomeOtherService(svcName);
}
return infoList
}
// other methods like the one above that return data for other things and in different ways but they
// are all public static, return data, and use a method from _dependecyGettingClass
}
}
我对带静态字段的静态类的理解是,类第一次调用字段实例化,之后就可以使用了。这是由我实际工作的代码支持的,例如:网站使用它来获取数据等
单元测试框架是否做了一些奇怪的事情并且没有像“典型的”c# 代码那样调用类?如果是这样,有没有办法更改 mstest 代码?
此外,在这种使用模式下,我的代码架构和设计是否正确?这个类(依赖于 _dataGettingClass 的一个实例)是否应该以不同的方式编写?
谢谢!
编辑: 调用该方法的单元测试类为:
namespace Foo.Test
{
[TestClass]
public class DataServiceTests
{
[TestMethod]
public void GetInfoListUsingServiceName()
{
string serviceName = "service001";
var result = DataService.GetServiceInfoList(serviceName);
Assert.IsNotNull(result);
}
}
}
解析内部异常引用的行是:
private static ClassINeedOneInstanceOf _dataGettingClass = new ClassINeedOneInstanceOf();
在数据服务类中
错误 {"Value cannot be null.\r\nParameter name: value"} 来自:
bool testDataOnly = Boolean.Parse(ConfigurationSettings["TestDataOnly"]);
最佳答案
测试框架使用的配置文件(web.config 或 app.config)缺少 "TestDataOnly"
的设置。
关于c# - 使用作为公共(public)依赖项的私有(private)静态字段对静态类进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16349960/