Skip to content

Instantly share code, notes, and snippets.

@GuyHarwood
Created November 26, 2013 15:18
Show Gist options
  • Save GuyHarwood/7660190 to your computer and use it in GitHub Desktop.
Save GuyHarwood/7660190 to your computer and use it in GitHub Desktop.
[TestFixture]
public class CustomHandleErrorAttributeTests
{
private CustomHandleErrorAttribute sut;
private ExceptionContext exceptionContext;
private readonly Mock<HttpRequestBase> mockRequest= new Mock<HttpRequestBase>();
private readonly Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();
private readonly Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();
[SetUp]
public void Setup()
{
sut = new CustomHandleErrorAttribute
{
ExceptionType = typeof(HttpException)
};
mockContext.Setup(htx => htx.Request)
.Returns(mockRequest.Object);
mockContext.Setup(htx => htx.Response)
.Returns(mockResponse.Object);
mockContext.Setup(htx => htx.IsCustomErrorEnabled)
.Returns(true);
exceptionContext = new ExceptionContext()
{
HttpContext = mockContext.Object,
Exception = new HttpException()
};
}
[Test]
public void WhenAlreadyHandledThenResultPreserved()
{
exceptionContext.ExceptionHandled = true;
sut.OnException(exceptionContext);
exceptionContext.Result.Should().BeOfType<EmptyResult>();
}
[Test]
public void WhenCustomErrorsNotEnabledThenResultPreserved()
{
mockContext.Setup(htx => htx.IsCustomErrorEnabled)
.Returns(false);
sut.OnException(exceptionContext);
exceptionContext.Result.Should().BeOfType<EmptyResult>();
}
[Test]
public void WhenExceptionTypeDiffersThenResultPreserved()
{
exceptionContext.Exception = new Exception();
sut.OnException(exceptionContext);
exceptionContext.Result.Should().BeOfType<EmptyResult>();
}
[Test]
public void WhenAjaxRequestThenResultIsJsonResult()
{
mockRequest.Setup(r => r.Headers)
.Returns(new NameValueCollection
{
{"X-Requested-With", "XMLHttpRequest"}
});
sut.OnException(exceptionContext);
exceptionContext.Result.Should().BeOfType<JsonResult>();
}
}
@avatasia
Copy link

Hi,I can't run this test case.
Can you tell me the name of the mock framework?
Thanks.

@nelsonwellswku
Copy link

I know this comment is over a year late, but the mock framework in this gist is Moq.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment