3

我不相信这种模式,但我正在尝试创建这样的测试:我想创建控制器,但将依赖项作为 Frozen 参数提供给测试。

测试如下。

    [Theory, AutoNSubstituteData]
    public void TestService(
           [Frozen] ITestService service, 
           TestController controller, 
           string value)
    {
        controller.Test(value);
        service.Received().ProcessValue(Arg.Any<string>());
    }

测试开始时出现此错误。

    System.InvalidOperationExceptionAn exception was thrown 
    while getting data for theory WebTest.Tests.Controllers.TestControllerRouteTests
    .TestService:
    System.Reflection.TargetInvocationException: 
    Exception has been thrown by the target of an invocation. ---> System.NotImplementedException:     The method or operation is not implemented.
       at System.Web.HttpContextBase.get_Items()
       at System.Web.WebPages.DisplayModeProvider.SetDisplayMode(HttpContextBase context, IDisplayMode displayMode)

我已经从这个AutoNSubstituteData帖子创建了 AutoNSubstituteData 属性。我试图创建一个虚假的上下文来解决这个问题。

/// <summary>
/// The auto n substitute data attribute.
/// </summary>
internal class AutoNSubstituteDataAttribute : AutoDataAttribute
{
    /// <summary>
    /// Initialises a new instance of the <see cref="AutoNSubstituteDataAttribute"/> class.
    /// </summary>
    internal AutoNSubstituteDataAttribute()
        : base(new Fixture()
        .Customize(new AutoNSubstituteCustomization())
        .Customize(new HttpContextBaseCustomization()))
    {
    }
}

internal class HttpContextBaseCustomization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.Customize<ViewContext>(_ => _.OmitAutoProperties());
        fixture.Customize<HttpContextBase>(_ => _.FromFactory(() => Substitute.For<HttpContextBase>()));
    }
}
4

2 回答 2

5

这里的问题实际上是HttpContextBase.Items邪恶,因为它是一个总是抛出.NotImplementedException

通常,模拟库默认不会覆盖虚拟成员,我怀疑 NSubstitute 也是如此。如果这是正确的,一种选择是配置 Test Double 以覆盖该Items属性。

HttpContext如果您在测试用例中不需要它,另一种选择是要求 AutoFixture 从控制器中省略该属性。

于 2014-10-27T15:36:40.973 回答
1

Mark Seemann 链接的其中一篇文章中,我们发现以下代码段为我们解决了这个问题-

fixture.Customize<ControllerContext>(c => c
            .Without(x => x.DisplayMode));
于 2017-02-27T05:10:43.937 回答