[英]How can I provide a methods implementation using Moq?
我有幾個方法的接口。 我有這個接口的默認實現。 出於集成測試的目的,我想創建一個模擬實現,如果調用其中一個方法,則返回我的自定義值,否則返回到默認實現。 是否可以使用Moq,或者我應該自己創建一個簡單的存根?
例
IInterface default = new DefaultImplementation();
var mock = new Mock<IInterface>();
mock.Setup(i => i.Method(It.IsAny<>())).Calls(p => p==0 ? return 5 : default.Method(p););
TheMethodITest(mock.Object()); //if it calls the object with 0 then it should get 5, otherwise it should call the default object
我不確定提供默認值或特定值的條件是什么。 但是,聽起來您想要使用Delegator
設置模擬實例。
public void MoqCanBeSetupWithDelegator()
{
var mock = new Mock<IInterface>();
Func<string, int> valueFunction = i => i == "true" ? 1 : default(int);
mock.Setup(x => x.Method(It.IsAny<string>())).Returns(valueFunction);
Assert.Equal(1, mock.Object.Method("true"));
Assert.Equal(0, mock.Object.Method("anonymous"));
}
public interface IInterface
{
int Method(string arg);
}
如您所見, Returns
方法被重載以接受表示模擬方法簽名的返回值( int
)或委托者。 您可以使用Func<string, int>
替換實際的實現 - int Method(string arg)
。
您可以通過將Mock設置為具體類並使用As()
來檢索基礎IInterface
來完成此設置。 然后,您可以硬鑄造mock.Object
來調用底層的具體對象:
[Test]
public void SomeTest()
{
var mock = new Mock<DefaultImplementation>().As<IInterface>();
mock.Setup(i => i.Method(It.IsAny<int>()))
.Returns<int>(p => p == 0
? 5
: ((DefaultImplementation)mock.Object).Method(p));
TheMethodITest(mock.Object);
}
這是我測試的其余設置,FWIW:
public interface IInterface
{
int Method(int p);
}
public class DefaultImplementation : IInterface
{
public int Method(int p)
{
return 6;
}
}
[TestFixture]
public class SomeFixture
{
public static void TheMethodITest(IInterface dep)
{
for (var i = 0; i < 10; i++)
{
Debug.WriteLine("{0}:{1}",i, dep.Method(i));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.