Anatoliy
Anatoliy

Reputation: 682

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

I use NUnit integration tests. I am trying to test to make sure that user can't create account with existing email. ([email protected])

I need to have test data in the database (account with [email protected] 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?

Upvotes: 4

Views: 328

Answers (3)

Matt Brunell
Matt Brunell

Reputation: 10399

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("[email protected]");   // OK

   // Act
   try
   {
      CreateAccount("[email protected]");

      // 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);
   }
}

Upvotes: 1

Paul Sasik
Paul Sasik

Reputation: 81557

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

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.

Upvotes: 5

RoelF
RoelF

Reputation: 7573

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).

Upvotes: 2

Related Questions