Skip to content

Instantly share code, notes, and snippets.

@alanta
Created March 27, 2020 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanta/90994b10fc2ff97d96e06a67d6dbbe09 to your computer and use it in GitHub Desktop.
Save alanta/90994b10fc2ff97d96e06a67d6dbbe09 to your computer and use it in GitHub Desktop.
Ensure your ASP.NET Core application can create all it's controllers
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace MyProject.Tests.Configuration
{
public class When_the_application_is_configured : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly WebApplicationFactory<Startup> _factory;
public When_the_application_is_configured(WebApplicationFactory<Startup> factory)
{
_factory = factory.WithWebHostBuilder(config =>
config.ConfigureAppConfiguration( (context, builder) =>
{
// force using local development settings here to ensure valid configuration
builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
.AddJsonFile($"appsettings.LocalDevelopment.json", optional: true, reloadOnChange: true);
}));
}
[Theory]
[MemberData(nameof(Controllers))]
[Trait("Category", "Integration")]
public void It_should_be_able_to_create_all_controllers(Type controller)
{
// Arrange
using var serviceScope = _factory.Services.CreateScope();
var serviceProvider = serviceScope.ServiceProvider;
// act
var service = serviceProvider.GetRequiredService(controller);
// Assert
service.Should().NotBeNull($"controllers of type {controller.Name} can be created");
}
public static IEnumerable<object[]> Controllers
{
get
{
// Note that this assumes all controllers are in the same assembly as the Startup class
return typeof(Startup)
.Assembly
.GetTypes()
.Where(t => typeof(ControllerBase).IsAssignableFrom(t))
.Select(t => new object[]
{
t
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment