简体   繁体   中英

How to write Unit Test for ExceptionHandler in WebAPI 2 using MoQ and NUnit

I have a WebAPI that uses a custom ExceptionHandler to handle all exceptions. How can I unit test this CustomExceptionHandler . Any lead will be helpful

public class CustomExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        try
        {
            context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, context.Exception));
        }
        catch (Exception)
        {
            base.Handle(context);
        }
    }

    public override bool ShouldHandle(ExceptionHandlerContext context)
    {
        return true;
    }
}

To unit test this custom exception handler create the dependencies needed by the sut/mut and exercise the test to verify the expected behavior.

Here is a simple example to get you started.

[TestClass]
public class CustomExcpetionhandlerUnitTests {
    [TestMethod]
    public void ShouldHandleException() {
        //Arrange
        var sut = new CustomExceptionHandler();
        var exception = new Exception("Hello World");
        var catchblock = new ExceptionContextCatchBlock("webpi", true, false);
        var configuration = new HttpConfiguration();
        var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/test");
        request.SetConfiguration(configuration);
        var exceptionContext = new ExceptionContext(exception, catchblock, request);
        var context = new ExceptionHandlerContext(exceptionContext);

        Assert.IsNull(context.Result);

        //Act
        sut.Handle(context);

        //Assert
        Assert.IsNotNull(context.Result);
    }
}

For the above test, only the necessary dependencies were provided in order to exercise the test. The method under test (mut) had one dependency on ExceptionHandlerContext . The minimal dependencies of this class for the test was provided to it before passing it to the mut.

The assertions can be expanded to suit the expected behaviors.

Since none of the dependencies were abstract, Moq would have been unable to wrap them. However this did not stop the manual instantiation of the classes needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM