bas
bas

Reputation: 14912

Integration tests repository class

Is it possible to change the database (entity framework) for integration tests, so that I can create test records in my database and throw everything away when the tests are done?

Now I am polluting the database that I use for local development.

PS: I realized this must be pretty basic stuff, but for some reason I am unable to find documentation on this.

Upvotes: 0

Views: 586

Answers (2)

bas
bas

Reputation: 14912

Found what I was looking for. Simply changing the database name is easier then I hoped for. You can change the database name by simply constructing the DbContext with a name.

new ApplicationContext("TestDatabase")

The implementation of the ApplicationContext:

public class ApplicationContext : DbContext, IDbContext
{
    public ApplicationContext()
    {
    }

    public ApplicationContext(string databaseName) : base(databaseName)
    {
    }
}

Running my tests I created a separate database that I can use for testing.

Upvotes: 0

eulerfx
eulerfx

Reputation: 37709

One way to achieve this is to wrap each test in a TransactionScope block, either explicitly for each test or in the setup method. If the scope is not committed, the changes are rolled back. Here is an example.

Upvotes: 3

Related Questions