3

I have a Setup method with many sql inserts. This method is called before every Test method.

The more tables I add to my database the bigger gets the Setup method and its hard to overview and maintain.

Sometimes I think I should make a private setup method for each test method so it would be less insert data for each test method but generally it would be more sql inserts than the former Setup method.

Often I also do not need some sql insert in the setup method for specific tests. Therefore I can not say easily which setup data is for which test method.

What have you found out is a good way?

Pascal
  • 12,265
  • 25
  • 103
  • 195
  • http://stackoverflow.com/questions/482827/database-data-needed-in-integration-tests-created-by-api-calls-or-using-importe?rq=1 - Found this very useful in the context of this question – Sairam Krish Oct 21 '14 at 06:41

1 Answers1

0

Consider using file resources (sql scripts to be precise). Having SQL stored as strings within class often ends up being maintainability nightmare.

In my C# projects what I usually do is:

  • create scripts inserting data required by given test (setup)
  • create script reverting database to its state before inserts (teardown)
  • add those scripts to project resources (so that they can be stored in .sql/text files and easily run on database when needed, and don't clutter class code)

And run them before/after test starts (within test method body though). For example (pseudocode):

public void DeleteClient_DeletesClientAndOrderHistory()
{
    ExecuteSql(Resources.Scripts.DeleteClientTest_SetupScript);
    // perform test 
    ExecuteSql(Resources.Scripts.DeleteClientTest_TeardownScript);
}

Of course, you wrap such constructs with catch-finally and assure other kinds of revert-to-starting point safety mechanisms. This however will have rather large impact on tests execution time. You can consider two extra options:

  • having class-wide setup and teardown, where you insert all data required by tested DAO class (runs once per class)
  • having assembly/namespace-wide setup and teardown, where you insert all data required by all DAO classes (runs once per all classes in assembly/namespace)

Naturally, you'll have to check whether your framework supports such methods (for example, NUnit does with [TestFixtureSetup] (class-wide) [SetUpFixture] (assembly/namespace-wide) attributes).

Community
  • 1
  • 1
k.m
  • 30,794
  • 10
  • 62
  • 86
  • actually I am talking about test-specific setup data vs general/class-wide setup data for all tests. – Pascal Jul 12 '12 at 17:40
  • @Pascal: yep I realize that - we do what I described; execute *test-targeted* SQL before and after each test. This essentially adds 2 lines of code to test (as in my pseudocode example), but is very easy to maintain. Yet, SQL is still *kind of* obscure; you might be better of with tools like [DbUnit](http://www.dbunit.org/) though. – k.m Jul 16 '12 at 20:49