background

Telerik JustMock

Mock Types and Members of Entity Framework

  • JustMock allows you to mock any dependency to a database through Entity Framework easily.
  • Part of the fastest, most flexible and complete mocking tool for crafting unit tests.
  • Our award-winning support team is available to assist you with any issues.
Mock everything
  • Mock of Entity Framework Overview

    Writing unit tests for code that have constant queries to a database is considered a slow process. One of the reasons is the developer has to make sure that the database has the correct data before the test execution starts and restore the initial state of that same data after the test ends. Such a unit test suite is hard to maintain when a change in the code or the database happens.

    JustMock allows you to mock any dependency to a database through Entity Framework easily.
    public class NerdDinners : DbContext
    {
        public DbSet<Dinner> Dinners { get; set; }
    }
     
    ...
     
    [TestMethod]
    public void ShouldReturnFakeCollectionWhenExpected()
    {
        // ARRANGE
        NerdDinners nerdDinners = new NerdDinners();
     
        // Arranging: When nerdDinners.Dinners GET is called,
        //            it should return the fake collection (fakeDinners).
        Mock.Arrange(() => nerdDinners.Dinners).ReturnsCollection(FakeDinners());
     
        // ACT - We call the nerdDinners.Dinners and search for a dinner with a certain DinnerID.
        var actualQuery = from d in nerdDinners.Dinners
                          where d.DinnerID == 1
                          select d;
     
        // ASSERT
        // We assert that the nerdDinners.Dinners collection will actually return a collection with 2 items.
        Assert.AreEqual(3, nerdDinners.Dinners.Count());
        // We assert that there is only one item in our collection and this item has DinnerID equal to one.
        Assert.AreEqual(1, actualQuery.Count());
        Assert.AreEqual(1, actualQuery.First().DinnerID);
    }

    Mock Entity Framework documentation
Next Steps