Skip to content

Commit

Permalink
📝 Testing with InMemory provider
Browse files Browse the repository at this point in the history
Resolves #95
  • Loading branch information
rowanmiller committed Jan 27, 2016
1 parent 365f8dc commit c8b79aa
Show file tree
Hide file tree
Showing 16 changed files with 831 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/miscellaneous/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ Miscellaneous
:caption: The following articles are available

logging
testing
105 changes: 105 additions & 0 deletions docs/miscellaneous/testing.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
Testing with InMemory
=====================

This article covers how to use the InMemory provider to write efficient tests with minimal impact to the code being tested.

.. caution::
Currently you need to use ``ServiceCollection`` and ``IServiceProvider`` to control the scope of the InMemory database, which adds complexity to your tests. We have a `feature on our backlog <https://github.com/aspnet/EntityFramework/issues/3253>`_ to provide an easier mechanism for controlling the scope of InMemory databases.

.. contents:: `In this article:`
:depth: 2
:local:

.. include:: /_shared/sample.txt
.. _sample: https://github.com/aspnet/EntityFramework.Docs/tree/master/docs/miscellaneous/testing/sample

When to use InMemory for testing
--------------------------------

The InMemory provider is useful when you want to test components using something that approximates connecting to the real database, without the overhead of actual database operations.

For example, consider the following service that allows application code to perform some operations related to blogs. Internally it uses a ``DbContext`` that connects to a SQL Server database. It would be useful to swap this context to connect to an InMemory database so that we can write efficient tests for this service without having to modify the code, or do a lot of work to create a test double of the context.

.. literalinclude:: testing/sample/BusinessLogic/BlogService.cs
:language: csharp
:linenos:
:lines: 6-29

InMemory is not a relational database
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

EF Core database providers do not have to be relational databases. InMemory is designed to be a general purpose database for testing, and is not designed to mimic a relational database.

Some examples of this include:
* InMemory will allow you to save data that would violate referential integrity constraints in a relational database.
* If you use DefaultValueSql(string) for a property in your model, this is a relational database API and will have no effect when running against InMemory.

.. tip::
For many test purposes these difference will not matter. However, if you want to test against something that behaves more like a true relational database, then consider using `SQLite in-memory mode <http://www.sqlite.org/inmemorydb.html>`_.

Get your context ready
----------------------

Avoid configuring two database providers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In your tests you are going to externally configure the context to use the InMemory provider. If you are configuring a database provider by overriding ``OnConfiguring`` in your context, then you need to add some conditional code to ensure that you only configure the database provider if one has not already been configured.

.. note::
If you are using ASP.NET Core, then you should not need this code since your database provider is configured outside of the context (in Startup.cs).

.. literalinclude:: testing/sample/BusinessLogic/BloggingContext.cs
:language: csharp
:linenos:
:lines: 17-23
:emphasize-lines: 3

Add a constructor for testing
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The simplest way to enable testing with the InMemory provider is to modify your context to expose a constructor that accepts an ``IServiceProvider`` and ``DbContextOptions<TContext>``.

.. literalinclude:: testing/sample/BusinessLogic/BloggingContext.cs
:language: csharp
:linenos:
:lines: 7-14
:emphasize-lines: 6-8

.. note::
``IServiceProvider`` is the container that EF will resolve all its services from (including the InMemory database instance). Typically, EF creates a single ``IServiceProvider`` for all contexts of a given type in an AppDomain. By allowing one to be passed in, you can control the scope of the InMemory database.

``DbContextOptions<TContext>`` tells the context all of it's settings, such as which database to connect to. This is the same object that is built by running the OnConfiguring method in your context.

Writing tests
-------------

The key to testing with this provider is the ability to tell the context to use the InMemory provider, and control the scope of the in-memory database. Typically you want a clean database for each test method.

Here is an example of a test class that uses the InMemory database. Each test method creates a new ``IServiceProvider``, meaning each method has its own InMemory database.

.. literalinclude:: testing/sample/TestProject/BlogServiceTests.cs
:language: csharp
:linenos:

Sharing a database instance for read-only tests
-----------------------------------------------

If a test class has read-only tests that share the same seed data, then you can share the InMemory database instance for the whole class (rather than a new one for each method). This means you have a single ``IServiceProvider`` for test class, rather than one for each test methof.

.. literalinclude:: testing/sample/TestProject/BlogServiceTestsReadOnly.cs
:language: csharp
:linenos:

Advanced: How to avoid modifying the context
--------------------------------------------

It is much more complicated, but you can avoid adding a constructor to your context. This approach leverages more advanced functionality of ``IServiceProvider``.

Here is an example that uses this approach. The important points are:
* Create a global ``ServiceCollection``, register the context as a service, and configure it to use the InMemory database.
* Create an ``IServiceProvider`` for each InMemory database instance you want (in this case, one per test method).
* Create an ``IServiceScope`` for each context instance you want, and resolve the context from it.

.. literalinclude:: testing/sample/TestProject/BlogServiceTestsAdvanced.cs
:language: csharp
:linenos:
8 changes: 8 additions & 0 deletions docs/miscellaneous/testing/sample/BusinessLogic/Blog.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace BusinessLogic
{
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
}
30 changes: 30 additions & 0 deletions docs/miscellaneous/testing/sample/BusinessLogic/BlogService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Collections.Generic;
using System.Linq;

namespace BusinessLogic
{
public class BlogService
{
private BloggingContext _context;

public BlogService(BloggingContext context)
{
_context = context;
}

public void Add(string url)
{
var blog = new Blog { Url = url };
_context.Blogs.Add(blog);
_context.SaveChanges();
}

public IEnumerable<Blog> Find(string term)
{
return _context.Blogs
.Where(b => b.Url.Contains(term))
.OrderBy(b => b.Url)
.ToList();
}
}
}
26 changes: 26 additions & 0 deletions docs/miscellaneous/testing/sample/BusinessLogic/BloggingContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using System;

namespace BusinessLogic
{
public class BloggingContext : DbContext
{
public BloggingContext()
{ }

public BloggingContext(IServiceProvider serviceProvider, DbContextOptions<BloggingContext> options)
: base(serviceProvider, options)
{ }

public DbSet<Blog> Blogs { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;");
}
}
}
}
134 changes: 134 additions & 0 deletions docs/miscellaneous/testing/sample/BusinessLogic/BusinessLogic.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{60B2C7AF-655F-4709-9E7F-7403E61F3A08}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BusinessLogic</RootNamespace>
<AssemblyName>BusinessLogic</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="EntityFramework.Core, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.Core.7.0.0-rc1-final\lib\net451\EntityFramework.Core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="EntityFramework.MicrosoftSqlServer, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.MicrosoftSqlServer.7.0.0-rc1-final\lib\net451\EntityFramework.MicrosoftSqlServer.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="EntityFramework.Relational, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.Relational.7.0.0-rc1-final\lib\net451\EntityFramework.Relational.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Caching.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Caching.Abstractions.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Caching.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Caching.Memory, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Caching.Memory.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Caching.Memory.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Configuration.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Abstractions.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Binder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Binder.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Configuration.Binder.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyInjection.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.DependencyInjection.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Logging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.Abstractions.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.OptionsModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.OptionsModel.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.OptionsModel.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Primitives, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Primitives.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Primitives.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Remotion.Linq, Version=2.0.0.0, Culture=neutral, PublicKeyToken=fee00910d6e5f53b, processorArchitecture=MSIL">
<HintPath>..\packages\Remotion.Linq.2.0.1\lib\net45\Remotion.Linq.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Collections.Concurrent" />
<Reference Include="System.Collections.Immutable, Version=1.1.36.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Collections.Immutable.1.1.36\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Diagnostics.DiagnosticSource, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Diagnostics.DiagnosticSource.4.0.0-beta-23516\lib\dotnet5.2\System.Diagnostics.DiagnosticSource.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Interactive.Async, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Ix-Async.1.2.5\lib\net45\System.Interactive.Async.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Transactions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Blog.cs" />
<Compile Include="BloggingContext.cs" />
<Compile Include="BlogService.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BusinessLogic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BusinessLogic")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("60b2c7af-655f-4709-9e7f-7403e61f3a08")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

0 comments on commit c8b79aa

Please sign in to comment.