2016-02-06 101 views
2

我有這種方式的C#代碼設置。模擬內部函數的響應,但測試外部函數

public class Client : IClient 
{ 
    public string funcA() 
    { 
     var output = funcB(1); 
     //Do something on output and produce finalResult 
     return finalResult; 
    } 

    public string funcB(int x) 
    { 
     // Some operations on produces string result 
     return result; 
    } 
} 

我想嘲笑funcB輸出,但讓funcA執行基於funcB的輸出。

在我的測試類我做到以下幾點:

public class MockClient 
{ 
    private Mock<IClient> _mockClient; 

    public MockClient() 
    { 
     _mockClient = new Mock<IClient>(); 
    } 

    [TestMethod] 
    public void TestClient() 
    { 
     _mockClient.Setup(foo => foo.funcB(It.IsAny<int>())).Returns("test"); 
     var testOutput = _mockClient.Object.funcA(); 
    } 
} 

變量testOutput返回NULL。我明白爲什麼,因爲該對象是從Interface創建的。我不知道如何正確解決這個問題。有關這方面的任何意見都會有所幫助

回答

1

我假設你基於你的語法使用Moq?如果是這樣,你可以使用「部分嘲笑」。例如:

變化funcB爲虛擬

public virtual string funcB(int x) 
{ 
    // Some operations on produces string result 
    return result; 
} 

然後嘲笑具體類型和CallBase屬性設置爲true:上述

[TestMethod] 
public void TestClient() 
{ 
    Mock<Client> _mockClient = Mock<Client>(); 
    _mockClient.CallBase = true; 
    _mockClient.Setup(foo => foo.funcB(It.IsAny<int>())).Returns("test"); 
    var testOutput = _mockClient.Object.funcA(); 
} 
+0

謝謝!這有幫助,但它甚至沒有使CallBase = true。這裏有什麼意義?也是關於製作虛擬的部分。 – Trancey

1

實施例是在Moq的語法完全正確。但是使這些功能變得虛擬或不真實 - 這是一個基於您的客戶等目的和需求的生產決策。將funcB改爲虛擬測試 - 聽起來不合理。

可以使用Typemock Isolator用於測試你的原代碼,請參閱:

 public class Client : IClient 
    { 
     public string funcA() 
     { 
      var output = funcB(1); 
      //Do something on output and produce finalResult 
      var finalResult = "B result: " + output; 
      return finalResult; 
     } 

     public string funcB(int x) 
     { 
      // Some operations on produces string result 
      return "result"; 
     } 
    } 

    [TestMethod, Isolated] 
    public void TestMethod() 
    { 
     //Arrange 
     var foo = new Client(); 
     Isolate.WhenCalled(() => foo.funcB(0)).WillReturn("test"); 

     //Act 
     var output = foo.funcA(); 

     //Assert 
     Assert.AreEqual("B result: test", output); 
    } 
相關問題