0

I'm new to C# and trying to write an integration test for a service. The service uses 2 providers as example below, and I don't know how to include them in my test. I'm using xUnit.

// Service

namespace App.Services
{
    public interface IProvider
    { }
    
    public class FirstProvider : IProvider
    { }

    public class SecondProvider : IProvider
    { }

    public class AppManager
    {
        private readonly IEnumerable<IProvider> _providers;

        public AppManager(
            IEnumerable<IProvider> providers)
        {
            _providers = providers;
        }

        public asyn Task ListItems()
        {
             foreach (var singleProvider in _providers) // When running test, I got ERROR here: _providers is null)
             {
                  // do something
             }
        }
    }
}

// Test

public class AppManagerTest
{
     private readonly IEnumerable<IProvider> _providers;

     [Fact]
     public async ListItems()
     {
          // Arrange
          var sut = new AppManager(_providers);

          // Act
          // Assert
     }
}

When running test, I got an error as pointed above in my service code. The error is System.NullReferenceException : Object reference not set to an instance of an object. Debugging the test shows that _providers is null.

So as I understood, my test does not get any of the providers. What should I do here?

lnhpt
  • 5
  • 3
  • 1
    Pass your providers to your test, for example `var sut = new AppManager(new IProvider[] { new FirstProvider(), new SecondProvider() });` – Martin Costello Apr 19 '22 at 16:31
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – gunr2171 Apr 19 '22 at 16:32
  • You might also want to have a look at the Moq library for C#: https://github.com/moq/moq4 – codehero Apr 19 '22 at 16:42
  • @MartinCostello thanks, this solves the problem – lnhpt Apr 21 '22 at 11:01

0 Answers0