Wednesday, November 15, 2017

Code sample for .Net Core Web Api Controller Integration Tests

Integration testing ensures the different parts of an application work correctly together. Unlike unit testing, integration tests frequently involve application dependencies such as database.

To get set up integration tests in .Net Core, you'll need a test project, add reference to your .Net Core Api project and a test runner. Magic is in the test host which comes with ASP.NET Core that can be added to integration test project and can be used to host .Net Core Apps, serving http requests with out the need for a real web host.

Following sample uses xUnit, FluentAssertions and TestHost to compose a simple integration test.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;
using Xunit;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using FluentAssertions;
using Microsoft.AspNetCore;


namespace VisualStudio99.Tests.IntegrationTests
{
    public class LookupApiControllerIntegrationTests 
    {
        private readonly HttpClient _client;
        private readonly TestServer _server;
        
       
        public LookupApiControllerIntegrationTests()
        {
            //_server = new TestServer(WebHost.CreateDefaultBuilder().UseUrls("http://localhost:5000").Configure(_ => { }));
            _server = new TestServer(new WebHostBuilder().UseStartup<Startup>().UseUrls("http://localhost:5000"));
            _client = _server.CreateClient();

            _client.BaseAddress = new Uri("http://localhost:5000");
            _client.DefaultRequestHeaders.Accept.Clear();
            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
        [Fact]
        public async Task Lookup_Get_All_EmployeeTypes()
        {
                var response = await _client.GetAsync($"/api/lookup/employeetypes");
                // Assert
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                var responseString = await response.Content.ReadAsStringAsync();
                var employeeTypes = JsonConvert.DeserializeObject<IEnumerable<EmployeeTypeDto>>(responseString);
                employeeTypes.Count().Should().Equals(5);
                employeeTypes.Should().OnlyHaveUniqueItems();
                employeeTypes.Should().OnlyContain(x => !string.IsNullOrEmpty(x.EmployeeTypeCode));
        }
    }