【问题标题】:How to write Unit Test for ExceptionHandler in WebAPI 2 using MoQ and NUnit如何使用 MoQ 和 NUnit 在 WebAPI 2 中为 ExceptionHandler 编写单元测试
【发布时间】:2017-03-06 09:53:32
【问题描述】:

我有一个使用自定义 ExceptionHandler 来处理所有异常的 WebAPI。我如何对这个CustomExceptionHandler 进行单元测试。任何线索都会有所帮助

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;
    }
}

【问题讨论】:

    标签: c# unit-testing asp.net-web-api2 nunit moq


    【解决方案1】:

    要对这个自定义异常处理程序进行单元测试,请创建 sut/mut 所需的依赖项并进行测试以验证预期行为。

    这里有一个简单的例子让你开始。

    [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);
        }
    }
    

    对于上述测试,仅提供了必要的依赖项以进行测试。被测方法 (mut) 对 ExceptionHandlerContext 有一个依赖项。在将其传递给 mut 之前,已向其提供了此类用于测试的最小依赖项。

    可以扩展断言以适应预期的行为。

    由于没有一个依赖是抽象的,Moq 将无法包装它们。然而,这并没有停止手动实例化所需的类。

    【讨论】:

    • 如果自定义的ExceptionHandler类需要RequestContext对象,你也要定义它: var exceptionContext = new ExceptionContext(exception: exception, catchBlock: catchblock, request: request) { RequestContext = new HttpRequestContext {配置 = 配置} };
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2011-04-25
    • 2014-10-03
    相关资源
    最近更新 更多