我想你應該爲你的模擬案例創建HWSysManager(或其他名稱)類,添加一些想要的方法,然後嘲笑它們。例如:
class HWSysManager
{
public virtual int ExampleReturnIntMethod(int a)
{
var someInt = 0;
return someInt;
}
,然後設置:
public void TestMethod()
{
Mock<HWSysManager> hwSysManager = new Mock<HWSysManager>();
hwSysManager.Setup(x => x.ExampleReturnInMethod(It.IsAny<int>())).Returns(10); //if parameter is any of int, return 10 in this case
}
然後使用您的嘲笑對象只使用 '對象' 屬性:
var hwSysInstance = hwSysManager.Object;
var result = hwSysInstance.ExampleReturnInMethod(2); //result will be 10 in this case - as we have mocked
在殼體上方的方法/屬性有是虛擬的。
可以使用接口也,你的情況:
public interface HwsysManager
{
int OpenConfiguration(string hwPath);
}
public void TestMethod()
{
Mock<HwsysManager> hwsysManager = new Mock<HwsysManager>();
hwsysManager.Setup(x => x.OpenConfiguration(It.IsAny<string>())).Returns(10);
}
這個模擬庫的所有功能描述如下: https://github.com/Moq/moq4/wiki/Quickstart
所以改變我的應用程序是不可避免的。即使如此,我如何從我的應用程序中調用「ProcessBias」?現在我稱之爲:'HWSysManager sm = new HWSysManager(); ProcessBias(sm,「」);' – Pablo
基本上我必須實現所有方法委託,我使用該庫。 – Pablo
您不應該在調用方法中創建實例。改爲從構造函數中獲取IHWSysManager。在你的開發機器中給出存根類作爲參數,並在實際環境中給出真正的實現類。這種技術被稱爲依賴注入,你可以閱讀關於它[這裏](http://stackoverflow.com/questions/130794/what-is-dependency-injection)。 –