Create controller in test using AutoNSubstituteData xUnit and AutoFixture

I'm not sure about the pattern, but I'm trying to create a test like this: I want to create a Controller, but I have dependencies available as Frozen parameters.

The test looks like this.

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

      

I am getting this error when running a test.

    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)

      

I created the AutoNSubstituteData attribute from this AutoNSubsituteData post . I tried to create a fake context to solve the problem.

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

      

+3


source to share


2 answers


The problem here is that HttpContextBase.Items is evil because it is a virtual property that always throws NotImplementedException

.

Library layouts generally don't override the default virtual principals, and I suspect this is the case for NSubstitute as well. If this is correct, one option would be to set the Test Double to override the property Items

.



Another option is to ask AutoFixture to omit the property HttpContext

from the controller if you don't need it in your test case.

+5


source


From one of the posts related to Mark Seemann , we found that the following piece of the solution to the problem for us is



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

      

+1


source







All Articles