AutoFixture 无法创建匿名 MVC 控制器 [英] AutoFixture fails to CreateAnonymous MVC Controller

查看:17
本文介绍了AutoFixture 无法创建匿名 MVC 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

IFixture fixture = new Fixture().Customize(new AutoMoqCustomization());
fixture.Customize<ViewDataDictionary>(c => c.Without(x => x.ModelMetadata));
var target = fixture.CreateAnonymous<MyController>();

异常:

System.Reflection.TargetInvocationException:System.Reflection.TargetInvocationException:已抛出异常通过调用的目标.---> System.NotImplementedException:方法或操作未实现.

System.Reflection.TargetInvocationException: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NotImplementedException: The method or operation is not implemented.

MyController() 接受 3 个参数.

我已经尝试了此处中描述的修复方法,但它不起作用.

I've tried the fix described in the answer here but it wouldn't work.

推荐答案

看起来,当使用 MVC 4 时,您必须以不同的方式自定义 Fixture 实例.

As it seems, when using MVC 4 you have to customize the Fixture instance in a different way.

如果您替换,测试应该通过:

The test should pass if you replace:

fixture.Customize<ViewDataDictionary>(c => c
    .Without(x => x.ModelMetadata));

:

fixture.Customize<ControllerContext>(c => c
    .Without(x => x.DisplayMode));

<小时>

或者,您可以创建所需自定义的组合:

internal class WebModelCustomization : CompositeCustomization
{
    internal WebModelCustomization()
        : base(
            new MvcCustomization(),
            new AutoMoqCustomization())
    {
    }

    private class MvcCustomization : ICustomization
    {
        public void Customize(IFixture fixture)
        {
            fixture.Customize<ControllerContext>(c => c
                .Without(x => x.DisplayMode));
        }
    }
}

那么,原来的测试可以改写为:

Then, the original test could be rewritten as:

[Fact]
public void Test()
{
    var fixture = new Fixture()
        .Customize(new WebModelCustomization());

    var sut = fixture.CreateAnonymous<MyController>();

    Assert.IsAssignableFrom<IController>(sut);
}

这篇关于AutoFixture 无法创建匿名 MVC 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆