AutoFixture fails to CreateAnonymous MVC Controller

狂风中的少年 提交于 2019-11-26 14:37:06

问题


The code:

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

the Exception:

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() takes 3 parameters.

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


回答1:


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

with:

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

Optionally, you can create a composite of the required customizations:

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


来源:https://stackoverflow.com/questions/14985930/autofixture-fails-to-createanonymous-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!