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 26, 2016
1 parent bf559df commit 179fae3
Show file tree
Hide file tree
Showing 15 changed files with 703 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
61 changes: 61 additions & 0 deletions docs/miscellaneous/testing.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
Testing with InMemory
=====================

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

.. 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:

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:
:emphasize-lines: 11

Controlling database and context scope
--------------------------------------

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

.. caution::
Currently you need to use ``ServiceCollection`` and ``IServiceProvider`` to control the scope of the 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.

Here is an example of a test class that uses the InMemory database. 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 you want** (using ``ServiceCollection.BuildServiceProvider``). Typically you want one database per test method.
* **Create an IServiceScope for each context instance you want.** This allows you to use a clean context for seeding the database, running the test, verifying data, etc.

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

A simplification 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).

.. literalinclude:: testing\sample\TestProject\BlogServiceReadOnlyTests.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();
}
}
}
17 changes: 17 additions & 0 deletions docs/miscellaneous/testing/sample/BusinessLogic/BloggingContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Microsoft.Data.Entity;

namespace BusinessLogic
{
public class BloggingContext : DbContext
{
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")]
24 changes: 24 additions & 0 deletions docs/miscellaneous/testing/sample/BusinessLogic/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework.Core" version="7.0.0-rc1-final" targetFramework="net461" />
<package id="EntityFramework.MicrosoftSqlServer" version="7.0.0-rc1-final" targetFramework="net461" />
<package id="EntityFramework.Relational" version="7.0.0-rc1-final" targetFramework="net461" />
<package id="Ix-Async" version="1.2.5" targetFramework="net461" />
<package id="Microsoft.Extensions.Caching.Abstractions" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Caching.Memory" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.Abstractions" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.Binder" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.DependencyInjection" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Logging" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Logging.Abstractions" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.OptionsModel" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Primitives" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Remotion.Linq" version="2.0.1" targetFramework="net461" />
<package id="System.Collections.Immutable" version="1.1.36" targetFramework="net461" />
<package id="System.Diagnostics.DiagnosticSource" version="4.0.0-beta-23516" targetFramework="net461" />
<package id="System.Diagnostics.Tracing" version="4.0.0" targetFramework="net461" />
<package id="System.Runtime" version="4.0.0" targetFramework="net461" />
<package id="System.Threading" version="4.0.0" targetFramework="net461" />
</packages>
28 changes: 28 additions & 0 deletions docs/miscellaneous/testing/sample/EFTesting.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BusinessLogic", "BusinessLogic\BusinessLogic.csproj", "{60B2C7AF-655F-4709-9E7F-7403E61F3A08}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestProject", "TestProject\TestProject.csproj", "{F4468750-9480-48E0-AA7A-DE84780AE1C2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{60B2C7AF-655F-4709-9E7F-7403E61F3A08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{60B2C7AF-655F-4709-9E7F-7403E61F3A08}.Debug|Any CPU.Build.0 = Debug|Any CPU
{60B2C7AF-655F-4709-9E7F-7403E61F3A08}.Release|Any CPU.ActiveCfg = Release|Any CPU
{60B2C7AF-655F-4709-9E7F-7403E61F3A08}.Release|Any CPU.Build.0 = Release|Any CPU
{F4468750-9480-48E0-AA7A-DE84780AE1C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F4468750-9480-48E0-AA7A-DE84780AE1C2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F4468750-9480-48E0-AA7A-DE84780AE1C2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F4468750-9480-48E0-AA7A-DE84780AE1C2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

0 comments on commit 179fae3

Please sign in to comment.