3
我有一个公共静态类我想单元测试使用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)
我试图测试的类是:
命名空间美孚。 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
}
}
我对带静态字段的静态类的理解是,第一次类是cal领导该领域实例化,并可以从那时起使用。这是由我的代码实际工作,前例如:网站使用它来获取数据等
是单元测试框架做一些奇怪的事情,而不是以“典型”的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();
在DataService类
错误{“值不能为空。\ r \ nParameter name:value”}来自:
bool testDataOnly = Boolean.Parse(ConfigurationSettings["TestDataOnly"]);
不知道'ClassINeedOneInstanceOf'类中发生了什么,我们无法帮助您找到问题。很明显,单元测试环境与应用程序环境相比有些不同。你忘了app/web.config中的connectionString或变量了吗? – 2013-05-03 01:14:51
查克 - 完全正确。事实证明,单元测试项目的app.config缺少web.config设置ClassINeddOneInstanceOf需要。 – 2013-05-03 01:21:11
错误出现在'bool.Parse'中,但是您没有显示调用该方法的代码。直到你做这个问题是无法回答的。 (或者至少显示足够的堆栈跟踪,除了'bool.Parse'外,它还显示*您的*代码。) – 2013-05-03 01:56:37