Search code examples
microsoft-fakes

Stubs with varying parameter


How does one stub a method in the Fakes framework so that the return value varies based on the value of a parameter?

For example, given the following interface and test, how does one create a stub in the case when value = 1 so that the return value = "A" and when value = 2, the return value = "B":

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);
}

Is this possible?


Solution

  • Here's the solution. I found a great resource on fakes over at Codeplex, which I'm sharing here for others to enjoy: 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);
    }