C# unit test with TestCase() attribute doesn't clean database/cache?

时间:2018-12-03 12:57:39

标签: c# database unit-testing nunit

Weird thing, hope you can help.

        [TestFixture]
        public class TestClass
        {

            [TestCase(Size.Big, Color.Blue)]
            [TestCase(Size.Big, Color.Red)]
            [TestCase(Size.Small, Color.Blue)]
            [TestCase(Size.Small, Color.Red)]
            public void TestChunkAndRun(Size a, Color b)
            {
                using (new TransactionScope())
                {
                     try
                     {
                         //Data generation + test
                     }
                     finally
                     {
                         //manually rollbacking, disposing objects
                     }

                }
          }

With this code, i am executing the unit test 4 times with different parameters. The unit test generates some data for the test itself. In the database 'Size' is part of a unique index, so it has to be unique.

The problem is that (no matter in what order the tests are executed) the 3rd and 4th testcases are ALWAYS failed due to duplicate row in database.

If I execute the tests one by one, separately, they pass. Only when I execute them as one group (no matter which order) the last 2 fail. Even when I manually rollback the transaction. The weird part is that the tables are empty indeed before each test. Somehow the data is being kept inbetween the TestCases so that i get Duplicate error

Any idea on what's happening?

Additional question: what's the difference between selecting multiple tests and clicking 'run all' & running the tests one by one

1 个答案:

答案 0 :(得分:0)

This post帮助我解决了问题。

在方法之外初始化了一些只读字段。将初始化转移到[TestInitialize] / [SetUp]方法后,它就像一个超级按钮一样工作。