2014-12-26 79 views
1

如何在Fakes框架中存根方法,以便返回值根據參數的值而變化?不同參數的存根

例如,給定以下接口和測試,在value = 1的情況下如何創建存根,以便返回值=「A」,當值= 2時,返回值=「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); 
} 

這可能嗎?

回答

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); 
} 
相關問題