Creating ASP.NET Core MVC Integration Tests – Getting Started

Tests should be created to make your life easier down the line. When you may or my not have to add new functionality or rework some previous code. However Unit tests may not always be enough, so we end up using integration testing as well.

Prerequisites :

*  You might run into some issues when trying to add the necessary using statements. Its a known issue (https://github.com/NuGet/Home/issues/4412).

In this post I will take about creating a test to check if a particular form is properly rendering as HTML.

Here is what your test controller should look like.

public class LoanFormShould
{
[Fact]
public async Task RenderApplicationForm()
{
// Creating a web Host Builder to put in your test server
var builder = new WebHostBuilder()
.UseContentRoot(@"Enter your Path here to project")
.UseEnvironment("Development")
.UseStartup<loans.Startup>()
.UseApplicationInsights(); // Only need this if your using that feature
var server = new TestServer(builder);
var client = server.CreateClient(); // creating a client to make a request
var response = await client.GetAsync("/Apply");
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync(); // Getting the string of HTML
Assert.Contains("New Loan Application", responseString); // Using the Assert Contains to see if the has the right title
}
}

You maybe asking at this point what about our database how will we actually be testing if our application performs CRUD operations properly ? Well for that we are going to being the In-memory database provider for Entity Framework. So that we never actually end up touching our actual DBs.

The only change you have to make once you have added the package is checking if you in development or not in your Startup.cs file. As seen below:

public void ConfigureServices(IServiceCollection services)
{
if (CurrentEnvironment.IsDevelopment()) // Here is where we check
{
services.AddDbContext<AppDbContext>(
options => options.UseInMemoryDatabase()); // And we ask it to use the InMemoryDatabase Option
}
else
{
services.AddDbContext<AppDbContext>(
options => options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
}
services.AddScoped<ICreditCardApplicationRepository,
EntityFrameworkCreditCardApplicationRepository>();
services.AddMvc();
}

view raw
InMemoryDBTesting.cs
hosted with ❤ by GitHub

And that is it. Now your ready to start integration testing in .NET Core MVC 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s