[TestClass]
public class MyTestClass
{
[TestMethod]
public void MyTestMethod(){
var mockRepository = new MockRepository();
var list = new List<Employee>
{
new Employee{ Id = 1},
new Employee{ Id = 2},
new Employee{ Id = 3}
}.AsQueryable();
var mockEntities = MockRepository.GenerateMock<Entities>();
IDbSet<Employee> mockDbSet= MockRepository.GenerateMock<IDbSet<Employee>, IQueryable>();
mockDbSet.AsQueryable().Stub(m => m.Provider).Return(list .Provider);
mockDbSet.AsQueryable().Stub(m => m.Expression).Return(list .Expression);
mockDbSet.AsQueryable().Stub(m => m.ElementType).Return(list .ElementType);
mockDbSet.AsQueryable().Stub(m => m.GetEnumerator()).Return(list .GetEnumerator());
mockEntities.Stub(x => x.Employees).PropertyBehavior();
mockEntities.Employees = mockDbSet as DbSet<Employee>;
int expected = list .Count();
var employeesService= mockRepository.PartialMock<EmployeesService>();
int actual = employeesService.GetCount();
Assert.AreEqual(expected, actual);
mockRepository.VerifyAll();
}
}
public partial class Entities : DbContext
{
public Entities()
: base("name=Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Employee> Employees
{ get; set; }}public class Employees
Service
{
Entities context;
public EmployeeService(Entities context)
{
this.context=context;
}
public int GetCount()
{
return context.Employees.Count();
}
}