繁体   English   中英

使用作为公共依赖项的私有静态字段对静态类进行单元测试

[英]Unit testing a static class with a private static field that is a common dependency

我有一个公共静态类,我正在尝试使用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)

我要测试的课程是:

namespace 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();

在DataService类中

错误{“值不能为空。\\ r \\ nParameter name:value”}来自:

bool testDataOnly = Boolean.Parse(ConfigurationSettings["TestDataOnly"]);

测试框架使用的配置文件(web.config或app.config)缺少"TestDataOnly"的设置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM