Last active
November 30, 2017 18:07
-
-
Save feanz/110eea0e4f96b1c25774 to your computer and use it in GitHub Desktop.
AutoMoq Web Api Controllers
This file contains 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 AutoMoqWebApiDataAttribute : AutoDataAttribute | |
{ | |
public AutoMoqWebApiDataAttribute() | |
: base(new Fixture().Customize(new AutoMoqWebApiCustomization())) | |
{ | |
} | |
} | |
public class AutoMoqWebApiCustomization : CompositeCustomization | |
{ | |
public AutoMoqWebApiCustomization() | |
: base(new HttpRequestMessageCustomization(), | |
new ApiControllerCustomization(), | |
new AutoMoqCustomization()) | |
{ | |
} | |
private class ApiControllerCustomization : ICustomization | |
{ | |
public void Customize(IFixture fixture) | |
{ | |
fixture.Customizations.Add( | |
new FilteringSpecimenBuilder( | |
new Postprocessor(new MethodInvoker(new ModestConstructorQuery()),new ApiControllerFiller()),new ApiControllerSpecification())); | |
} | |
private class ApiControllerFiller : ISpecimenCommand | |
{ | |
public void Execute(object specimen, ISpecimenContext context) | |
{ | |
if (specimen == null) | |
throw new ArgumentNullException("specimen"); | |
if (context == null) | |
throw new ArgumentNullException("context"); | |
var target = specimen as ApiController; | |
if (target == null) | |
throw new ArgumentException( | |
"The specimen must be an instance of ApiController.", | |
"specimen"); | |
target.Request = | |
(HttpRequestMessage)context.Resolve( | |
typeof(HttpRequestMessage)); | |
} | |
} | |
private class ApiControllerSpecification : IRequestSpecification | |
{ | |
public bool IsSatisfiedBy(object request) | |
{ | |
var requestType = request as Type; | |
return requestType != null && typeof(ApiController).IsAssignableFrom(requestType); | |
} | |
} | |
} | |
private class HttpRequestMessageCustomization : ICustomization | |
{ | |
public void Customize(IFixture fixture) | |
{ | |
fixture.Customize<HttpRequestMessage>(c => c | |
.Without(x => x.Content) | |
.Do(x => x.Properties[HttpPropertyKeys.HttpConfigurationKey] = new HttpConfiguration())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment