具有不同参数的存根

时间:2014-12-26 22:31:42

标签: microsoft-fakes

如何在Fakes框架中存根一个方法,以便返回值根据参数的值而变化?

例如,给定以下接口和测试,在value = 1的情况下如何创建存根,以便返回值=“A”,当值= 2时,返回值=“B”:< / p>

public interface ISimple
{
  string GetResult(int value);
}

public class Sut
{
    ISimple simple;

    public Sut(ISimple simple) 
    {
        this.simple = simple;
    }

    public string Execute(int value)
    {
        return this.simple.GetResult(value);
    }
}

[TestMethod]
public void Test()
{
    StubISimple simpleStub = new StubISimple();
    simpleStub.GetResultInt32 = (value) => { return "A";} // Always returns "A"

    var sut = new Sut(simpleStub);

    // OK
    var result = sut.Execute(1)
    Assert.AreEqual("A", result);

    // Fail
    result = sut.Execute(2);
    Assert.AreEqual("B", result);
}

这可能吗?

1 个答案:

答案 0 :(得分:1)

这是解决方案。我在Codeplex找到了很多关于假货的资源,我在这里分享其他人可以享受: http://vsartesttoolingguide.codeplex.com/releases/view/102290

[TestMethod]
public void Test()
{
    StubISimple simpleStub = new StubISimple();
    simpleStub.GetResultInt32 = (value) => { 
        switch(value) 
        {
            case "A":
            {
                return "A";
                break;
            }
            case "B":
            {
                return "B";
                break;
            {
        }
    }

    var sut = new Sut(simpleStub);

    // OK
    var result = sut.Execute(1)
    Assert.AreEqual("A", result);

    // OK
    result = sut.Execute(2);
    Assert.AreEqual("B", result);
}