开发者

Where is the best place to create test data in TDD?

开发者 https://www.devze.com 2023-01-25 14:56 出处:网络
I use NUnit integration tests. I am trying to 开发者_运维百科test to make sure that user can\'t create account with existing email. (test@example.com)

I use NUnit integration tests. I am trying to 开发者_运维百科test to make sure that user can't create account with existing email. (test@example.com)

I need to have test data in the database (account with test@example.com email).

I can create this account in the test function, or in the sql script (and run it before integration tests).

Where is the better place to create this test data?


Neither option is wrong but there are a number of ways to extend and solidify your strategy:

  • Mocking which goes hand-in-hand with TDD
  • Generation of db test data with tools like RedGate's Sql Data Gen
  • Creation of pluggable data providers (IoC/DI) where you can swap between test and production

None of these solutions are mutually exclusive. I would recommend the last item especially (pluggable provider) and then a choice between object mocking or faux but quality db test data.


Your best bet is to look into Dependency Injection and Mocking frameworks. This way you can swap out data providers with mocked data providers and use the data that fits your needs for the specific test.

If you're using NHibernate or similar, you can always recreate your db schema before each test(fixture).


In a situation like you describe, I would prefer to create the account in the test function.

A unit test should be as self contained as possible. Also, it helps to be able to understand what you are testing, if you can see all the data required for the test in one place.

Here's a totally made up example that should illustrate:

[Test]
public void Test_CannotCreateDuplicateEmail()
{
   // Arrange
   CreateAccount("test@example.com");   // OK

   // Act
   try
   {
      CreateAccount("test@example.com");

      // If control arrives here, then the test has failed.
      Assert.Fail();
   }

   // Assert
   catch(AccountException ex)
   {
        // Assert that the correct exception has been thrown.
        Assert.AreEqual("Failed", ex.Message);
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号