2013-04-22 41 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