Visual Studio C# unit testing - Run Unit test with varied/multiple test initializations, Run same unit test multiple times?

我的梦境 提交于 2019-12-03 13:26:26

In nUnit you can use the [TestCase] attribute for simple types:

[Test]
[TestCase("a", "b")]
[TestCase("c", "b")]
[TestCase("a", "d")]
public void TestMethod(string param1, string param2){
   // run your test with those parameters
}

Or you can use a TestCaseSource method for complex types:

[Test]
[TestCaseSource("GetTestCases")]
public void TestMethod(MyObject1 param1, MyObject2 param2){
   // run your test with those parameters
}

private IEnumerable GetTestCases(){
   yield return new TestCaseData( new MyObject1("first test args"), 
                                  new MyObject2("first test args"))
                        .SetName("SomeMeaningfulNameForThisTestCase" );
   yield return new TestCaseData( new MyObject1("2nd test args"), 
                                  new MyObject2("2nd test args"))
                        .SetName("SomeMeaningfulNameForThisTestCase2" );

}

You can do something similar in MS-Test using a DataSource: http://codeclimber.net.nz/archive/2008/01/18/How-to-simulate-RowTest-with-MS-Test.aspx

You might be able to do this without needing any framework-specific addons by creating an abstract base class that contains all your test functions, then inheriting that base class with multiple classes, each with their own setup function.

public abstract class MyTests
{
    [Test]
    public void TestOne()
    {
        ...
    }

    [Test]
    public void TestTwo()
    {
        ...
    }
}
[TestFixture]
public class FirstSetup : MyTests
{
    [Setup]
    public void Setup()
    {
        ...
    }
}

[TestFixture]
public class SecondSetup : MyTests
{
    [Setup]
    public void Setup()
    {
        ...
    }
}

I have done this in other languages, but not sure how the various C# frameworks will handle it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!