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.
- Microsoft.AspNetCore.TestHost – NuGet Package
- Microsoft.EntityFrameworkCore.InMemory – NuGet Package
* 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|
|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")|
|.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");|
|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|
|options => options.UseInMemoryDatabase()); // And we ask it to use the InMemoryDatabase Option|
|options => options.UseSqlServer(|
And that is it. Now your ready to start integration testing in .NET Core MVC 🙂