Is it possible to use Dependency Injection with xUnit?

前端 未结 4 1217
忘掉有多难
忘掉有多难 2021-02-06 22:25

I have a test class with a constructor that needs an IService.

public class ConsumerTests
{
    private readonly IService          


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-06 22:57

    What are you trying to test? The implementation of IService or the wiring of the DI container?

    If you are testing IService implementations, you should be instantiating them directly in the test (and mocking any dependencies):

    var service = new MyServiceImplementation(mockDependency1, mockDependency2, ...);
    // execute service and do your asserts, probably checking mocks
    

    If you are trying to test the wiring of the DI container, you need to reach out and grab the configured container explicitly. There is no "composition root" that will do that for you (pseudo-code follows, kind of Autofac flavored):

    var myContainer = myCompositionRoot.GetContainer();
    var service = myContainer.ResolveCompnent();
    // execute service and do your asserts with the actual implementation
    

    If you are using xUnit for running integration tests where you need to use the same object in multiple tests, look at Fixtures: http://xunit.github.io/docs/shared-context.html.

提交回复
热议问题