我有一個具有私有構造函數並通過公共靜態方法(單例類)訪問的類。無法在假貨中創建此類的單例對象。假靜態/單類/使用微軟假貨的方法
public class MyBusinessManager : BusinessManager
{
private MyBusinessManager objMyBusinessManager;
private MyBusinessManager (MyBusinessManager dvqsDataManager)
{
objMyBusinessManager= dvqsDataManager;
}
public static MyBusinessManager GetInstance() // out
{
MyBusinessManager dvqsDataMgr = new MyBusinessManager();
return new MyBusinessManager (dvqsDataMgr);
}
public bool MyBusinessManagerMethod (int bm)
{
if(bm == 0)
return true;
return false;
}
}
我想測試一下下面的方法:
public class MyService
{
public bool MyServiceMethod(int serviceParam)
{
MyBusinessManager dvqBusinessManager = MyBusinessManager.GetInstance(); // make fake call
return dvqBusinessManager.MyBusinessManagerMethod(serviceParam); // make fake service call
}
}
我的測試類:
[TestClass]
public class MyService_UT
{
[TestMethod]
public void TestMethod1()
{
using (ShimsContext.Create())
{
ShimMyBusinessManager.GetInstance =() => { return new ShimMyBusinessManager(); };
ShimMyBusinessManager.AllInstances.MyServiceMethodInt32 = (a) =>{
return true;
}
MyService obj = new MyService();
Assert.IsTrue(obj.MyServiceMethod(1))// doesn't call fake method
}
}
}
如何調用在這種情況下,假的方法?無法使用此代碼創建假實例。
您剛剛瞭解到單身人士是「反模式」的原因之一 – Joe
正確。這是舊代碼。但如何擺脫這一點? – user2323308
重構糟糕的舊代碼可能會更容易,而不是將另一層糟糕的代碼放在頂層來測試它。 – nvoigt