Writing a Unit Test

Follow these steps to write a unit test for our application:

  1. Let's create a unit test. Let's name it RestBuy.Test, as shown in the following screenshot:

  1. Rename UnitTest1.cs to EFTest and copy appsettings.json from your web project to the test project. But change the database name to RestBuy_Test.
Make sure you add references to all other projects from Test. You also need a reference to Microsoft.EntityFramework.Core, and then install Microsoft.Extensions.Configuration from NuGet.

Your project should look as shown here:

  1. Now, ensure your appsettings.json file resembles this:
{
"ConnectionStrings":
{
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;
Database=RestBuy_Test;Trusted_Connection=True;
MultipleActiveResultSets=true"
},
"Logging":
{
"IncludeScopes": false,
"LogLevel":
{
"Default": "Warning"
}
}
}
  1. Right-click on the appsettings.json file from Properties ensure it is deployed to the output folder by selecting Copy if newer for the Copy to Output Directory option:
  2. Ensure your EFTest file also resembles this:

Go to https://goo.gl/NK99He to access the code.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RestBuy.Entities;
using RestBuy.Infrastructure.EF;
using System.IO;
using System.Threading.Tasks;
namespace RestBuy.Test
{
...
...
}

This test basically creates our database, saves a product to the database in one context, then queries it in another context and commits it.