Data-driven testing in NUnit?

前端 未结 5 1760
情歌与酒
情歌与酒 2020-12-14 03:40

In MSTest you can do something like:

[TestMethod]
[DataSource(\"Microsoft.VisualStudio.TestTools.DataSource.CSV\", 
            \"testdata.csv\", \"testdata#         


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-14 03:56

    I got csv based data driven testing in NUnit working as follows:

    Use the csv reader from code project, wrapped up in a private method returning IEnumerable in your test class, and then reference this with a TestCaseSource attribute on your test cases. Include your csv file in your project and set "Copy to Output Directory" to "Copy Always".

    using System.Collections.Generic;
    using System.IO;
    using LumenWorks.Framework.IO.Csv;
    using NUnit.Framework;
    
    namespace mytests
    {
        class MegaTests
        {
            [Test, TestCaseSource("GetTestData")]
            public void MyExample_Test(int data1, int data2, int expectedOutput)
            {
                var methodOutput = MethodUnderTest(data2, data1);
                Assert.AreEqual(expectedOutput, methodOutput, string.Format("Method failed for data1: {0}, data2: {1}", data1, data2));
            }
    
            private int MethodUnderTest(int data2, int data1)
            {
                return 42; //todo: real implementation
            }
    
            private IEnumerable GetTestData()
            {
                using (var csv = new CsvReader(new StreamReader("test-data.csv"), true))
                {
                    while (csv.ReadNextRecord())
                    {
                        int data1 = int.Parse(csv[0]);
                        int data2 = int.Parse(csv[1]);
                        int expectedOutput = int.Parse(csv[2]);
                        yield return new[] { data1, data2, expectedOutput };
                    }
                }
            }
        }
    }
    

    original post at: http://timwise.blogspot.com/2011/05/data-driven-test-in-nunit-with-csv.html

提交回复
热议问题