我無法讓Moq模擬靜態方法中創建的對象。 這裏是我的起訂量和代碼Moq靜態類中的對象
代碼:
public interface IConfigHelper
{
string GetConfiguration(string sectionName, string elementName);
}
public class ConfigHelper : IConfigHelper
{
public ConfigHelper() { }
public virtual string GetConfiguration(string sectionName, string elementName)
{
string retValue = String.Empty;
//Does things to get configuration and return a value
return retValue;
}
}
public class myRealClass
{
public myRealClass(){}
public string myworkingMethod()
{
var retValue = String.Empty;
retValue = utilSvc.GetConfigurationValue();
return retValue;
}
}
public static class utilSvc
{
public static string GetConfigurationValue()
{
ConfigHelper configUtil = new ConfigHelper(); //NOT BEING MOCKED
return configUtil.GetConfiguration("sectionName/sectionElement", "ClinicalSystem");
}
}
使用起訂量
[TestFixture(TestName = "Tests")]
public class Tests
{
private Mock<IConfigHelper> configHelperMOCK;
[SetUp]
public void Setup()
{
configHelperMOCK = new Mock<IConfigHelper>();
}
[Test]
public void serviceIsBPManagementForValidSource()
{
//Arrange
string sectionName = "sectionName/sectionElement";
string clinicalElementName = "ClinicalSystem";
string clinicalElementValue = "Zedmed";
configHelperMOCK.Setup(s => s.GetConfiguration(sectionName, clinicalElementName)).Returns(clinicalElementValue);
//act
// the call to myRealClass
//assert
// test assertions
}
}
測試
,我遇到的問題是這一行:
ConfigHelper configUtil = new ConfigHelper(); //NOT BEING MOCKED
我無法獲得moq來模擬物體。 我不想讓代碼讀取配置文件。我希望模仿這個實例ConfigHelper
我不是想嘲笑一個靜態類!我試圖嘲笑一個靜態方法內創建的類。該方法是靜態的,因爲它是Ninject的Bind <>()使用的方法。WithConstructorArgument必須是靜態的。 – GregJF
你應該仍然注入對象。同時確保你在沒有並行的情況下運行你的測試,許多測試運行者並行運行測試,當涉及靜態類時這是不安全的。 –
另外,就靜態類而言,它通常可以讓它成爲一個單例,因此您仍然可以爲程序實例化實例,同時爲程序提供靜態單個實例。 –