I am creating the Entity Framework ObjectContext per ASP.NET Request using the following code:
public static class ObjectContextPerRequest
{
public static EStudyTestDatabaseEntities Context
{
get
{
var _context = HttpContext.Current.Items["EStudyModel"] as EStudyTestDatabaseEntities;
if(_context == null)
{
_context = new EStudyTestDatabaseEntities();
HttpContext.Current.Items.Add("EStudyModel", _context);
}
return _context;
}
}
public static void RemoveContext()
{
var _context = HttpContext.Current.Items["EStudyModel"] as EStudyTestDatabaseEntities;
if(_context != null)
{
_context.Dispose();
}
}
}
In the Repository I use it like this:
public class RoleRepository : IRoleRepository
{
public IList<Role> GetAll()
{
using(var db = ObjectContextPerRequest.Context)
{
return db.RoleSet.ToList();
}
}
}
This works fine if I run the application. The problem is how I will unit test the Repository because I need to create a HttpContext.
[TestFixture]
public class when_getting_all_roles
{
[Test]
public void should_get_roles_successfully()
{
var repository = new RoleRepository();
Assert.AreNotEqual(4,repository.GetAll());
}
}
UPDATE:
I can make IObjectContextPerRequest interface and ObjectContextPerRequest as shown below:
public interface IObjectContextPerRequest
{
EStudyTestDatabaseEntities Context { get; }
void RemoveContext();
}
And now I can write my test as follows:
[TestFixture]
public class when_getting_all_roles
{
[Test]
public void should_get_roles_successfully()
{
var objectContextPerRequestStub = MockRepository.GenerateStub<IObjectContextPerRequest>();
objectContextPerRequestStub.Expect(x => x.Context).Return(new EStudyTestDatabaseEntities());
var repository = new RoleRepository(objectContextPerRequestStub);
Assert.AreNotEqual(4,repository.GetAll());
}
}