簡體   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