0

Can Autofac inject dependencies into my test class?

Consider the test class (I've kept the example generic as I'll use whatever framework gives me this capability).

public class SimpleTest {

   private IService _service;

   public SimpleTest(IService service) 
   {
       _service = service;
   }

   public void TestMethod() {
   {
       // do something with service
   }
}

That IService type is provided by autofac. So now when I run my test method I want various dependencies coming from autofac to have been injected. I don't mind if it has to use field injection - I can make them public if necessary.

Maybe there is some kind of test runner I can register that can do this "preconfiguration"?

Michael Wiles
  • 20,902
  • 18
  • 71
  • 101
  • Does this snaswer your question? [Is it possible to use Dependency Injection with xUnit?](https://stackoverflow.com/questions/39131219/is-it-possible-to-use-dependency-injection-with-xunit) – canton7 Oct 22 '21 at 07:36
  • I didn't tag it as xunit.net... it's tagged as xunit (unit testing in general) but it seems that xunit is the only that's tried to implement this – Michael Wiles Oct 22 '21 at 08:21
  • In the .NET world, "xUnit" invariably refers to the unit test framework with that name – canton7 Oct 22 '21 at 08:25

1 Answers1

0

Thanks for your responses.

I added a custom base class that does this for me...

Here is the code for MSTest (which is what I'm using).

 [TestInitialize]
 public void InjectAutofacDependencies()
 {
      var fieldInfos = this.GetType().GetFields(
         BindingFlags.DeclaredOnly |
         BindingFlags.NonPublic | BindingFlags.Instance);

      foreach (var fieldInfo in fieldInfos)
      {
          var resolveOptional = 
              _container.ResolveOptional(fieldInfo.FieldType);
          if (resolveOptional != null)
          {
               fieldInfo.SetValue(this, resolveOptional);
          }
      }
  }

I'd have preferred constructor injection but this will more than suffice.

Michael Wiles
  • 20,902
  • 18
  • 71
  • 101