Skip to content

Instantly share code, notes, and snippets.

@christopherbauer
Last active August 29, 2015 14:23
Show Gist options
  • Save christopherbauer/4e78e92e7a4bf3ba8c36 to your computer and use it in GitHub Desktop.
Save christopherbauer/4e78e92e7a4bf3ba8c36 to your computer and use it in GitHub Desktop.
HttpContextFactory + Test
public class ExampleController : Controller
{
private readonly IConfigurationReader _configurationReader;
private readonly IHttpContextFactory _httpContextFactory;
public MaintenanceController(IConfigurationReader configurationReader, IHttpContextFactory httpContextFactory)
{
_configurationReader = configurationReader;
_httpContextFactory = httpContextFactory;
}
public ActionResult Index()
{
var users = _configurationReader.GetMaintenanceUsers();
var roles = _configurationReader.GetMaintenanceRoles();
if (users.IndexOf(_httpContextFactory.GetContext().User.Identity.Name, StringComparison.CurrentCultureIgnoreCase) > 0 ||
roles.Split(',').Any(s => _httpContextFactory.GetContext().User.IsInRole(s))) //if user name
{
return View();
}
return new EmptyResult();
}
}
public class ControllerTests
{
[TestFixture]
public class when_getting_index
{
[Test]
public void then_should_return_view()
{
// Arrange
var configurationReader = new Mock<IConfigurationReader>();
configurationReader.Setup(reader => reader.GetMaintenanceRoles()).Returns(string.Empty);
configurationReader.Setup(reader => reader.GetMaintenanceUsers()).Returns(string.Empty);
var identity = new Mock<IIdentity>();
identity.Setup(identity1 => identity1.Name).Returns(string.Empty);
var principal = new Mock<IPrincipal>();
principal.Setup(principal1 => principal1.Identity).Returns(identity.Object);
var httpContextBase = new Mock<HttpContextBase>();
httpContextBase.Setup(@base => @base.User).Returns(principal.Object);
var httpContextFactory = new Mock<IHttpContextFactory>();
httpContextFactory.Setup(factory => factory.GetContext()).Returns(httpContextBase.Object);
var controller = new MaintenanceController(configurationReader.Object, httpContextFactory.Object);
// Act
var viewResult = controller.Index();
// Assert
Assert.That(viewResult, Is.Not.Null);
}
}
}
// ReSharper disable ClassNeverInstantiated.Global
public class HttpContextFactory : IHttpContextFactory
// ReSharper restore ClassNeverInstantiated.Global
{
public HttpContextBase GetContext()
{
if(HttpContext.Current == null) throw new InvalidOperationException("HttpContext is null");
return new HttpContextWrapper(HttpContext.Current);
}
}
public class HttpContextFactoryTests
{
[TestFixture]
public class when_creating_httpcontext
{
[Test]
public void then_should_return_type_of_http_context()
{
// Arrange
var factory = new HttpContextFactory();
// Act // Assert
Assert.Throws<InvalidOperationException>(() => factory.GetContext());
}
}
}
public interface IHttpContextFactory
{
HttpContextBase GetContext();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment