2016-09-06 140 views
1

我理解使用DI來確定依賴關係並嘲笑它們進行單元測試。但是,當我有多個實現當前功能的單元測試時,我如何將它們注入到單元測試中。使用DI進行單元測試

例如:快速排序或歸併

public class TestSort 
{ 
    ISort sort = null; 
    [TestInitialize] 
    public void Setup() 
    { 
     sort = new MergeSort(); // or any implementation which need to be injected on setup 
    } 
+1

Parametrised測試可能是一種選擇,但有一個讀[這裏](http://stackoverflow.com/questions/9021881/how-to-run- a-test-method-with-multiple-parameters-in-mstest)關於使用MsTest並不容易。 – kayess

+0

@ kayess這很有趣 – Pacchy

回答

3

如果你想測試你的「排序」的方法,你應該爲每個排序算法獨立的單元測試。例如

[TestMethod] 
public void MergeSort_SortUnderorderedList_ShouldSortListCorrectly() 
{ 
    // Arrange 
    ISort sort = new MergeSort(); 

    // Act 
    int[] sortedList = sort.Sort(new int[] { 4, 2, 18, 5, 19 }); 

    // Assert 
    Assert.AreEqual(2, sortedList[0]); 
    Assert.AreEqual(4, sortedList[1]); 
    Assert.AreEqual(5, sortedList[2]); 
    Assert.AreEqual(18, sortedList[3]); 
    Assert.AreEqual(19, sortedList[4]);  
} 

[TestMethod] 
public void QuickSort_SortUnderorderedList_ShouldSortListCorrectly() 
{ 
    // Arrange 
    ISort sort = new QuickSort(); 

    // Act 
    int[] sortedList = sort.Sort(new int[] { 4, 2, 18, 5, 19 }); 

    // Assert 
    Assert.AreEqual(2, sortedList[0]); 
    Assert.AreEqual(4, sortedList[1]); 
    Assert.AreEqual(5, sortedList[2]); 
    Assert.AreEqual(18, sortedList[3]); 
    Assert.AreEqual(19, sortedList[4]); 
} 

當你寫你的測試爲你注入一個排序算法爲一類,你不應該測試排序算法是否可以正常工作在該測試。相反,您應該注入排序算法模擬並測試Sort()方法被調用(但不測試該測試中排序算法的正確結果)。

此示例使用起訂量做嘲諷

public class MyClass 
{ 
    private readonly ISort sortingAlgorithm; 

    public MyClass(ISort sortingAlgorithm) 
    { 
     if (sortingAlgorithm == null) 
     { 
     throw new ArgumentNullException("sortingAlgorithm"); 
     } 
     this.sortingAlgorithm = sortingAlgorithm; 
    } 

    public void DoSomethingThatRequiresSorting(int[] list) 
    { 
     int[] sortedList = this.sortingAlgorithm.Sort(list); 

     // Do stuff with sortedList 
    } 
} 

[TestClass] 
public class MyClassTests 
{ 
    [TestMethod] 
    public void DoSomethingThatRequiresSorting_SomeCondition_ExpectedResult() 
    { 
     // Arrange - I assume that you need to use the result of Sort() in the 
     // method that you're testing, so the Setup method causes sortingMock 
     // to return the specified list when Sort() is called 
     ISort sortingMock = new Mock<ISort>(); 
     sortingMock.Setup(e => e.Sort().Returns(new int[] { 2, 5, 6, 9 })); 
     MyClass myClass = new MyClass(sortingMock.Object); 

     // Act 
     myClass.DoSomethingThatRequiresSorting(new int[] { 5, 9, 2, 6 }); 

     // Assert - check that the Sort() method was called 
     myClass.Verify(e => e.Sort(It.IsAny<int[]>)); 
    } 
} 
+0

你有沒有注意到OP使用MsTest而不是NUnit? – kayess

+0

@kayess NUnit和我的答案有什麼關係? –

+0

@ben你的答案的第一部分是我需要消除的。而且我確定我會用於依賴關係,我很清楚這一點。 – Pacchy