Search code examples
autofacxunit2

XUnit Test with autofac


I followed this link https://github.com/dennisroche/xunit.ioc.autofac to create XUnit Test with autofac, but I got error

The requested service 'Xunit.Sdk.TestOutputHelper' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency. I have added below code:

        builder.Register(context => new TestOutputHelper())
            .As<ITestOutputHelper>()
            .InstancePerLifetimeScope();

Did I miss anything from above link?


Solution

  • TL;DR:

    Make sure to register the type TestOutputHelper also as self when using this library.

    Longer version:

    The AutofacTestInvoker (https://github.com/dennisroche/xunit.ioc.autofac/blob/master/src/xunit2.ioc.autofac/AutofacTestInvoker.cs) needs the concrete class TestOutputHelper (not ITestOutputHelper!) to call TestOutputHelper.Initialize(IMessageBus, ITest), which is not available in the Interface, and resolves it via the created ILifetimeScope. In your example you register it as it's interface, so for Autofac there is no TestOutputHelper available to resolve at all.

    EDIT: The documentation has been adapted. See https://github.com/dennisroche/xunit.ioc.autofac/pull/9 for details.