Progress Telerik JustMock

Mock Types and Members of Entity Framework

Nasa, Visa, Microsoft Fox, Samsung, IBM World Bank Group, Volvo
  • 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
Background-NextSteps

Next Steps

See Plans & Pricing

Purchase individual products or any of the bundles

Download Free Trial

With dedicated technical support.