Created
May 22, 2018 13:57
-
-
Save geirsagberg/aabf41854527d669ed7c8e42a1990761 to your computer and use it in GitHub Desktop.
Unit test that ensures all MediatR requests have one handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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