Skip to content

Instantly share code, notes, and snippets.

@KevinDJones
Created November 14, 2018 14:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KevinDJones/f9dce0e790ff2784ec3aba4aaf8a8353 to your computer and use it in GitHub Desktop.
Save KevinDJones/f9dce0e790ff2784ec3aba4aaf8a8353 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Formatting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.WebApiCompatShim;
using Microsoft.Extensions.Options;
using Moq;
namespace Messaging.Tests
{
public static class TestHelpers
{
public static HttpRequestMessage SetupHttp(HttpRequestMessage requestMessage)
{
var services = new Mock<IServiceProvider>(MockBehavior.Strict);
var formatter = new XmlMediaTypeFormatter();
var context = new DefaultHttpContext();
var contentNegotiator = new Mock<IContentNegotiator>();
contentNegotiator
.Setup(c => c.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>()))
.Returns(new ContentNegotiationResult(formatter, mediaType: null));
var options = new WebApiCompatShimOptions();
if (formatter == null)
{
options.Formatters.AddRange(new MediaTypeFormatterCollection());
}
else
{
options.Formatters.Add(formatter);
}
var optionsAccessor = new Mock<IOptions<WebApiCompatShimOptions>>();
optionsAccessor.SetupGet(o => o.Value).Returns(options);
services.Setup(s => s.GetService(typeof(IOptions<WebApiCompatShimOptions>))).Returns(optionsAccessor.Object);
if (contentNegotiator != null)
{
services.Setup(s => s.GetService(typeof(IContentNegotiator))).Returns(contentNegotiator);
}
context.RequestServices = CreateServices(contentNegotiator.Object, formatter);
requestMessage.Properties.Add(nameof(HttpContext), context);
return requestMessage;
}
private static IServiceProvider CreateServices(
IContentNegotiator contentNegotiator = null,
MediaTypeFormatter formatter = null)
{
var options = new WebApiCompatShimOptions();
if (formatter == null)
{
options.Formatters.AddRange(new MediaTypeFormatterCollection());
}
else
{
options.Formatters.Add(formatter);
}
var optionsAccessor = new Mock<IOptions<WebApiCompatShimOptions>>();
optionsAccessor.SetupGet(o => o.Value).Returns(options);
var services = new Mock<IServiceProvider>(MockBehavior.Strict);
services.Setup(s => s.GetService(typeof(IOptions<WebApiCompatShimOptions>))).Returns(optionsAccessor.Object);
if (contentNegotiator != null)
{
services.Setup(s => s.GetService(typeof(IContentNegotiator))).Returns(contentNegotiator);
}
return services.Object;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment