2015-07-02 42 views
1

我有一個工廠類返回一個代表像下面(GetDelegate法)如何測試使用起訂量和NUnit

public interface IFactory 
{ 
    Func<int, string> GetDelegate(bool isValid); 
} 

public class AFactory : IFactory 
{ 
    private readonly IService1 _service1; 
    private readonly IService2 _service2; 

    public AFactory(IService1 service1, IService2 service2) 
    { 
     _service1 = service1; 
     _service2= service2; 
    } 

    public Func<int, string> GetDelegate(bool isValid) 
    { 
     if (isValid) 
      return _service1.A; 
     return _service2.B; 
    } 
} 

public interface IService1 
{ 
    string A(int id); 
} 

public interface IService2 
{ 
    string B(int id); 
} 

我一直在嘗試寫GetDelegate單元測試,但不知道如何斷言委託具體Func鍵返回根據的isValid

我的單元測試的嘗試是像下面(這我不開心)

[Test] 
    public void ShouldReturnCorrectMethod() 
    { 
     private var _sut = new AFactory(new Mock<IService1>(), new Mock<IService2>()); 

     var delegateObj = _sut.GetDelegate(true); 
     Assert.AreEqual(typeof(string), delegateObj.Method.ReturnType); 
     Assert.AreEqual(1, delegateObj.Method.GetParameters().Count()); 
    } 

任何幫助是非常讚賞

感謝

回答

2

一種方法是嘲笑調用IService1.AIService2.B,在完全相同的方式,如果你是直接打電話給他們的結果。然後,您可以檢查當您致電退還的委託人時,您會得到預期的答案(並且已撥打相應的服務)。

+0

謝謝。是的,這應該有所幫助。出於好奇,這是工廠模式的「正確」使用嗎?我真的不是真的返回一個類實例本身? –

+0

@nesh_s:那麼你正在返回一個值...它不需要只是一個類。這有點不尋常,但並不特別令人擔憂。 –

1
[Test] 
public void GetDelegate_WhenCalledWithIsValidTrue_ReturnsDelegateA() 
{ 
    // Arrange 
    Mock<IService1> service1Mock = new Mock<IService1>(); 
    Mock<IService2> service2Mock = new Mock<IService2>(); 

    string expectedResultA = "A"; 
    string expectedResultB = "B"; 

    service1Mock.Setup(s => s.A(It.IsAny<int>())).Returns(expectedResultA); 
    service2Mock.Setup(s => s.B(It.IsAny<int>())).Returns(expectedResultB); 

    var _sut = new AFactory(service1Mock.Object, service2Mock.Object); 

    // Act 
    Func<int, string> delegateObj = _sut.GetDelegate(true); 

    // Assert 
    string result = delegateObj(0); 
    Assert.AreEqual<string>(expectedResultA, result); 
}