When do I use the TestFixtureSetUp attribute instead of a default constructor?

前端 未结 9 1106
旧巷少年郎
旧巷少年郎 2021-01-30 15:59

The NUnit documentation doesn\'t tell me when to use a method with a TestFixtureSetup and when to do the setup in the constructor.

public class MyTe         


        
相关标签:
9条回答
  • 2021-01-30 16:28

    One thing you can't do with [TestFixtureSetup] that you can do in the constructor is receive parameters from the [TestFixture] .

    If you want to parameterise your test fixture, then you will have to use the constructor for at least some of the set-up. So far, I've only used this for integration tests, e.g. for testing a data access layer with multiple data providers:

    [TestFixture("System.Data.SqlClient",
      "Server=(local)\\SQLEXPRESS;Initial Catalog=MyTestDatabase;Integrated Security=True;Pooling=False"))]
    [TestFixture("System.Data.SQLite", "Data Source=MyTestDatabase.s3db")])]
    internal class MyDataAccessLayerIntegrationTests
    {
        MyDataAccessLayerIntegrationTests(
            string dataProvider,
            string connectionString)
        {
            ...
        }
    }
    
    0 讨论(0)
  • 2021-01-30 16:33

    [TestFixtureSetUp] and [TestFixtureTearDown] are for whole test class. runs only once.

    [SetUp] and [TearDown] are for every test method(test). runs for every test.

    0 讨论(0)
  • 2021-01-30 16:35

    I think this has been one of the issues that hasn't been addressed by the nUnit team. However, there is the excellent xUnit project that saw this exact issue and decided that constructors were a good thing to use on test fixture initialization.

    For nunit, my best practice in this case has been to use the TestFixtureSetUp, TestFixtureTearDown, SetUp, and TearDown methods as described in the documentation.

    I think it also helps me when I don't think of an nUnit test fixture as a normal class, even though you are defining it with that construct. I think of them as fixtures, and that gets me over the mental hurdle and allows me to overlook this issue.

    0 讨论(0)
提交回复
热议问题