2013-04-22 44 views
1

如何將數據從testrunner傳遞給unittest?將數據傳遞給nunit testcase

例如一個output pathinterface configuration的主機?

+0

如果你這樣做, – 2013-04-22 15:16:26

+0

我們不使用'nunit'來測試主機上的軟件,我們正在驗證一個微控制器平臺,因此我們需要例如計算機上的可用接口來連接到微控制器。 – Razer 2013-04-22 15:18:53

+0

與運行集成測試的方式沒有多大區別。例如針對數據庫運行一些數據庫代碼。某處你有一個名稱,用戶名,密碼等配置文件。這可能會很痛苦,但它不是一個單元測試。 – 2013-04-22 15:30:37

回答

2

你可能已經完成了一個不同的途徑,但我會盡我所能分享這一點。在後2.5版的NUnit中,實現了通過外部源驅動測試用例的能力。我做了一個使用CSV文件的簡單示例演示。

CSV是包含我的兩個測試輸入和預期結果的東西。所以1,1,2爲第一等等。

CODE

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.IO; 
using System.Text; 
using System.Threading.Tasks; 
using NUnit.Framework; 
namespace NunitDemo 
{ 
    public class AddTwoNumbers 
    { 
     private int _first; 
     private int _second; 

     public int AddTheNumbers(int first, int second) 
     { 
      _first = first; 
      _second = second; 

      return first + second; 
     } 
    } 

    [TestFixture] 
    public class AddTwoNumbersTest 
    { 

     [Test, TestCaseSource("GetMyTestData")] 
     public void AddTheNumbers_TestShell(int first, int second, int expectedOutput) 
     { 
      AddTwoNumbers addTwo = new AddTwoNumbers(); 
      int actualValue = addTwo.AddTheNumbers(first, second); 

      Assert.AreEqual(expectedOutput, actualValue, 
       string.Format("AddTheNumbers_TestShell failed first: {0}, second {1}", first,second)); 
     } 

     private IEnumerable<int[]> GetMyTestData() 
     { 
      using (var csv = new StreamReader("test-data.csv")) 
      { 
       string line; 
       while ((line = csv.ReadLine()) != null) 
       { 
        string[] values = line.Split(','); 
        int first = int.Parse(values[0]); 
        int second = int.Parse(values[1]); 
        int expectedOutput = int.Parse(values[2]); 
        yield return new[] { first, second, expectedOutput }; 
       } 
      } 
     } 
    } 
} 

然後,當你與NUnit的UI看起來運行它(我包括例如目的失敗:

enter image description here

+0

好的例子謝謝。我可以建議更改TestCaseSource(「GetMyTestData」)以使用nameof - TestCaseSource(nameof(GetMyTestData)),該方法也需要是靜態的 – wnbates 2016-12-14 12:19:42