Testy oparte na danych w NUnit?

W MSTest możesz zrobić coś takiego:

[TestMethod]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", 
            "testdata.csv", "testdata#csv", DataAccessMethod.Sequential)]
public void TestSomething()
{
    double column1 = Convert.ToDouble(TestContext.DataRow["column1"]);
    ...
    Assert.AreEqual(...);
}

Jaki jest odpowiednik kodu w NUnit 2.5?

Author: SteveC, 2010-10-27

4 answers

Spojrzałbym na sparametryzowaną dokumentację testów w NUnit 2.5 i zobaczmy, czy możesz zrobić coś takiego jak to, co tam robisz. Nie przypominam sobie, aby NUnit miał wbudowany atrybut odczytu CSV do testów sparametryzowanych. Może jednak gdzieś istnieć wtyczka społecznościowa.

Powinienem również zwrócić uwagę, że jeśli szukasz nie-MS Unit Testing Framework libraries, które Ci pomogą, xUnit.net ma tę funkcjonalność. Sprawdź ten wpis na blogu od Bena Hall

 7
Author: Dave White,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-27 19:34:46

Mam csv oparte na danych driven testing w NUnit działa w następujący sposób:

Użyj czytnika csv z projektu code , zamkniętego w prywatnej metodzie zwracającej liczbę w klasie testowej, a następnie odwołaj się do tego z atrybutem TestCaseSource w swoich przypadkach testowych. Dołącz swój plik csv do projektu i ustaw "Copy to Output Directory " na " 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<int[]> 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

 12
Author: Tim Abell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-23 10:12:07

Oto kolejny przykład bardzo podobny do Tima Abella, który jednak nie używa frameworka dla czytnika CSV i pokazuje specyfikę testu. Uwaga kiedy używasz TestCaseAttribute TestAttribute można pominąć.

        [TestCaseSource("GetDataFromCSV")]
    public void TestDataFromCSV(int num1,int num2,int num3)
    {
        Assert.AreEqual(num1 + num2 ,num3);
    }

    private IEnumerable<int[]> GetDataFromCSV()
    {
        CsvReader reader = new CsvReader(path);
        while (reader.Next())
        {
            int column1 = int.Parse(reader[0]);
            int column2 = int.Parse(reader[1]);
            int column3 = int.Parse(reader[2]);
            yield return new int[] { column1, column2, column3 };
        }
    }


public class CsvReader : IDisposable
{
    private string path;
    private string[] currentData;
    private StreamReader reader;

    public CsvReader(string path)
    {
        if (!File.Exists(path)) throw new InvalidOperationException("path does not exist");
        this.path = path;
        Initialize();
    }

    private void Initialize()
    {
        FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
        reader = new StreamReader(stream);
    }

    public bool Next()
    {
        string current = null;
        if ((current = reader.ReadLine()) == null) return false;
        currentData = current.Split(',');
        return true;
    }

    public string this[int index]
    {
        get { return currentData[index]; }
    }


    public void Dispose()
    {
        reader.Close();
    }
}

DANE CSV:

10,200,210 20,190,210 30,180,210 40,170,210 50,160,210 60,150,210 70,140,210 80,130,210 90,120,210 100,110,210

Uwaga: Trzecia kolumna jest sumą dwóch pierwszych kolumn i zostanie to potwierdzone w jednostce test.

Wyniki:

wyniki

Znajdź poniżej alternatywę, używając obiektów TestCaseData i ustawiając Typ powrotu (który poza kursem jest obowiązkowy)

        [TestCaseSource("GetDataFromCSV2")]
    public int TestDataFromCSV2(int num1, int num2)
    {
        return num1 + num2;
    }

    private IEnumerable GetDataFromCSV2()
    {
        CsvReader reader = new CsvReader(path);
        while (reader.Next())
        {
            int column1 = int.Parse(reader[0]);
            int column2 = int.Parse(reader[1]);
            int column3 = int.Parse(reader[2]);
            yield return new TestCaseData(column1, column2).Returns(column3);
        }
    }
 3
Author: Thulani Chivandikwa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-24 12:18:27

Myślę, że NUnit equivilent jest oznaczanie metody jako metody setup, a następnie załadować dane do pola, które mają być wykorzystane w kolejnych testach.

Musisz to zakodować sam, mniej więcej.

 -2
Author: wllmsaccnt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-27 19:29:17