1
\$\begingroup\$

I've made integration tests for a major part of my application. I test my dependency injection is set up correctly, creating controllers with it's dependencies going all the way to the database (using localDB) and returning the response. I'm looking for what could be improved.

Here is the general concept of my tests:

public class TestDbInitializer : DropCreateAlways<MyContext>() { public static List<Item> Items; public override Seed(DbContext context) { Items = new List<Item>(); // Adding items // .. Items.ForEach(x => context.Add(x)); context.SaveChanges(); } } public class BaseTransactionsTests { private TransactionScope _scope [TestInitialize] public void Initialize() { _scope = new TransactionScope(); } [TestCleanup] public void Cleanup() { _scope.Dispose(); } } [TestClass] public class IntegrationTests : BaseTransactionsTests { private IDependenciesContainer _container; public static void AssemblyInit(TestContext context) { Database.SetInitializer(new TestDbInitializer()); _container = new DependenciesContainer(); // Registers all my application's dependencies _container.RegisterAll(); } [TestInitialize] public void Initialize() { using (var context = new MyContext("TestsDatabase")) { context.Initialize(true); } } [TestMethod] public void TestAddItem() { var controller = _container.Resolve<MyController>(); var result = controller.AddItem(new Item({Name = "Test"})) var goodResult = result as OkNegotiatedResult<string>(); if (result == null) Assert.Fail("Bad result") using (var context = new MyContext("TestsDatabase")) { Assert.AreEqual(context.Items.Count, TestDbInitializer.Items.Count + 1) } } } 

I use my dependency injector in my tests, registering all dependencies once (AssemblyInitialize).

I created a DB instance for testings, and a specific DropCreateAlways initializer with a fake data Seed method, which I set as the initializer in the AssemblyInitialize as well.

I want to reseed the database with my fake data before each test run. For that case I implemented the base class which holds a transaction scope.

When I run my tests, the following exception is thrown when seeding the database in the TestInitialize:

DROP DATABASE statement cannot be used inside a user transaction

How should I deal with it?

Is there a way I can stimulate a real Http request, so that my ModelState.IsValidvalidation will function as it does when running the real thing? Are there any more ways I can improve those testings?

\$\endgroup\$
1
  • \$\begingroup\$This belongs at StackOverflow. It's a question, not a review.\$\endgroup\$CommentedApr 18, 2016 at 7:07

1 Answer 1

0
\$\begingroup\$

I eneded up initializing the database of my tests in the AssemblyInitialize instead of in TestInitialize. This way my database is created once at the beginning of all tests, and after each test it is rolled back to contain only thr content of the Seeding

\$\endgroup\$