Skip to content

Instantly share code, notes, and snippets.

@geirsagberg
Created May 22, 2018 13:57
Show Gist options
  • Save geirsagberg/aabf41854527d669ed7c8e42a1990761 to your computer and use it in GitHub Desktop.
Save geirsagberg/aabf41854527d669ed7c8e42a1990761 to your computer and use it in GitHub Desktop.
Unit test that ensures all MediatR requests have one handler
public class RequestHandlerTests
{
[Fact]
public void All_requests_have_matching_handlers()
{
var assembly = typeof(Program).Assembly;
var types = assembly.ExportedTypes.ToList();
var requestTypes = types.Where(t => t.Implements<IBaseRequest>());
Type GetHandlerType(Type requestType)
{
if (requestType.Implements<IRequest>()) {
return typeof(IRequestHandler<>).MakeGenericType(requestType);
}
var genericRequestType = requestType.GetInterfaces().Single(i => i.Implements<IBaseRequest>() && i.GetGenericArguments().Length == 1);
var resultType = genericRequestType.GenericTypeArguments.Single();
return typeof(IRequestHandler<,>).MakeGenericType(requestType, resultType);
}
foreach (var requestType in requestTypes) {
var handlerType = GetHandlerType(requestType);
var matchingTypes = types.Where(t => handlerType.IsAssignableFrom(t)).ToList();
matchingTypes.Count.Should().Be(1, $"{requestType.Name} should have exactly one handler");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment