O'Reilly logo

Programming Entity Framework: DbContext by Rowan Miller, Julia Lerman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Considering Automated Testing with DbContext

In this book, we’ve used a console application to demonstrate many of the features that you’ve learned about. This is to ensure that readers using the Express and Standard versions of Visual Studio are able to follow along. Our personal preference when building applications, however, is to include automated tests, whether we use the testing tools built into Visual Studio Professional and Visual Studio Ultimate, or third-party tools such as XUnit, NUnit, or the testing features in JetBrain’s Resharper.

To be able to build flexible tests, you’ll want to leverage the IDbSet interface. The DbSet class you’ve worked with throughout this book implements IDbSet. And the IDbSet interface is where the Add, Attach, Remove, and Create methods come from. IDbSet also implements IQueryable<T>, which enables LINQ and brings along the extension methods: Find, Include, and AsNoTracking.

First, let’s look at examples of automated tests that you can build and run with the existing BreakAwayContext class and without having to work with the IDbSet.

Testing with DbSet

You can build unit tests to validate that your classes work as expected without engaging Entity Framework or the database.

For example, the simple test listed in Example 8-5 checks that the FullName property in the Person type functions as expected.

Example 8-5. Ensuring that FullName works as expected

  [TestMethod()]
  public void PersonFullNameReturnsFirstNamePlusLastName()
  {
    var person = new Person ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required