Easy DbContext Integration Test with Effort
April 13, 2014 Leave a comment
If you are mocking your DbContext to realize yours integration tests, certainly you are spend your time. I always thought that mock context is a hard job and conducive to bug. Another day after watch the video tutorial about Integration Test I went search some library or framework that help me do it about Entity Framework DbContext. In my search I found (many asks/comments in StackOverflow :P) Effort. Effort is a “In Memory Database“, simple, easy to configure, very useful and c# based!
Installation
You can download de last version here. Or; You can install using Nuget Package Manager. Entity Framework 5: Install-Package Effort -Pre Entity Framework 6: Install-Package Effort.EF6 -Pre
Usage
The SampleContext’s constructor is needed because we pass an fake instance of DbConnection created by Effort library. To factory Effort DbConnection instance we can use:
- Effort.DbConnectionFactory.CreateTransient(); – The “CreateTransient” method always returns new instance of DbConnection, in other words, always we call this method we lost previous operations inside the context.
- Effort.DbConnectionFactory.CreatePersistent(“whatever”); – The “CreatePersistent” method can be used when you want something like a session. The data will persist in memory.
// Your POCO:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
private Person() { }
public Person(string name)
{
Name = name;
}
}
// Your DbContext
public class SampleContext : DbContext
{
public SampleContext(DbConnection dbConnection) : base(dbConnection, true)
{
}
public DbSet<Person> People { get; set; }
}
// My Program
class Program
{
static void Main(string[] args)
{
var sampleContext = new SampleContext(Effort.DbConnectionFactory.CreateTransient());
sampleContext.People.Add(new Person("Jaspion"));
sampleContext.People.Add(new Person("Jiraya"));
sampleContext.SaveChanges();
}
}
See in the act:
The next examples is the almost same that exists in the Effort’s blog, but was typed by me. 🙂 I liked this example.
//
// Using the Transient.
//
class Program
{
static void Main(string[] args)
{
var sampleContext = new SampleContext(Effort.DbConnectionFactory.CreateTransient());
sampleContext.People.Add(new Person("Jaspion"));
sampleContext.People.Add(new Person("Jiraya"));
sampleContext.SaveChanges();
// Output 1
Console.WriteLine("Transient output 1 - Total People: {0}", sampleContext.People.Count());
sampleContext = new SampleContext(Effort.DbConnectionFactory.CreateTransient());
sampleContext.People.Add(new Person("Jaspion"));
sampleContext.People.Add(new Person("Jiraya"));
sampleContext.SaveChanges();
// Output 2
Console.WriteLine("Transient output 2 - Total People: {0}", sampleContext.People.Count());
Console.ReadKey();
}
}
Output 1: “Transient output 1 – Total People: 2”
Output 2: “Transient output 2 – Total People: 2”