I'm trying to use Moq
to make some tests for Entity Framework Code First classes. I'm very new to Moq and mocking techniques and I wonder if it's possible to easily do a test that I will describe below. I searched through the web for some solutions, but most are based on repository pattern, which I want to avoid.
I have ITestEntities
interface for context
public interface ITestEntities
{
IDbSet<Order> Orders { get; }
IDbSet<Product> Products { get; }
IDbSet<User> Users { get; }
}
Then context
public class TestEntities : DbContext, ITestEntities
{
public TestEntities() : base("name=TestEntities")
{
}
public virtual IDbSet<Order> Orders { get; set; }
public virtual IDbSet<Product> Products { get; set; }
public virtual IDbSet<User> Users { get; set; }
}
A controller and an action to test
public class HomeController : Controller
{
private ITestEntities db;
public HomeController()
{
db = new TestEntities();
}
public HomeController(ITestEntities db)
{
this.db = db;
}
public ActionResult Index()
{
var count = db.Users.Count();
ViewBag.count = count;
return View(count);
}
}
And finally a NUnit test using Moq
[Test]
public void ModelValueShouldBeTwo()
{
var mockUsers = new Mock<IDbSet<User>>();
mockUsers.Setup(m => m.Count()).Returns(2);
var mockDB = new Mock<ITestEntities>();
mockDB.Setup(db => db.Users).Returns((IDbSet<User>)mockUsers);
var controller = new HomeController((ITestEntities)mockDB);
var view = controller.Index();
Assert.IsInstanceOf<ViewResult>(view);
Assert.AreEqual(((ViewResult)view).Model, 2);
}
The problem is with this line: mockUsers.Setup(m => m.Count()).Returns(2);
. When running this test I get following error:
System.NotSupportedException : Expression references a method that does not belong to the mocked object: m => m.Count<User>()
I think this is due to .Count()
being a static method so it cannot be mocked by Moq. Is there a way to test this simple action using Moq and not using full-fledged repository pattern, which as I understand should anyway have this .Count()
part hardcoded into some method to be testable... Maybe I just use the mocks in a wrong way? Because I have impression that this should be quite simple and possible with EF Code First.