Mr. Boy
Mr. Boy

Reputation: 63718

Share DB setup data between multiple unit test classes

I'm not sure if true unit tests should strictly interact with external systems like databases, but mine do - the idea being my setup code ensures the DB is in a certain state, then my unit tests expect certain results from methods that get called; I need to check the DB-access code is doing the right thing.

I want to use the same DB test data in multiple test classes and not copy-paste it into each class' [TestInitialize] and I'm wondering how best to do this. Options seem to include:

  1. Throw it all in an external .sql script and run this
  2. Some sort of helper class with a static method

I would prefer the code to update the DB is part of my C# code but wondered if there is a more typical way MSTest projects might handle this?

Upvotes: 1

Views: 661

Answers (1)

Nkosi
Nkosi

Reputation: 247088

You could use inheritance to share setup data between multiple unit test classes.

You could create a base test class and have the other classes inherit it (including the [TestInitialize] which will be called for each test).

Take a look at this article, Structuring Unit Tests, that shows how to use a test structure for tests that have common setup code for all tests

Using the above link for reference a test structure could look like...

[TestClass]
public partial class DbTests {
    protected DbContext db;    

    [TestInitialize]
    public virtual void Init() { 
        //Virtual so it could be overridden in derived classes if needed.
        //...check the DB-access code is doing the right thing. 
    }

    [TestClass]
    public class Test1 : DbTests {
        [TestMethod]
        public void Should_Do_Some_Test(){...}

        [TestMethod]
        public void Should_Do_Some_Db_Test(){...}
    }

    [TestClass]
    public class Test2 : DbTests {
        [TestMethod]
        public void Should_Do_Some_Other_Test(){...}
    }    
}

I use the above format to structure my tests that share common setup code.

Upvotes: 2

Related Questions