静的メソッドで作成されたオブジェクトをモックにすることはできません。 は、ここに私の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
Iオブジェクトをモックするためにmoqを取得することはできません。 私は、コードが設定ファイルを読み込まないようにします。私はこのインスタンスをmoqから外したいですConfigHelper
に、私は静的クラスをモックしようとしているわけではない、それをリダイレクトすることができます!私は静的メソッド内で作成されたクラスを模擬しようとしています。このメソッドは、NinjectのBind <>()。WithConstructorArgumentで使用されるメソッドであるため静的です。静的でなければなりません。 – GregJF
オブジェクトを挿入する必要があります。また、並列性を持たずにテストを実行していることを確認してください。多くのテストランナーがテストを並行して実行します。静的クラスを使用する場合は安全ではありません。 –
また、クラスが静的であるという点では、代わりにシングルトンにすることができます。したがって、静的な単一インスタンスをプログラムで使用できるようにしながら、テスト用のインスタンスをインスタンス化できます。 –