0

May I enquire if I am mocking my IConfiguration correctly as I keep get a null error. I am trying to mock my controller where it reads the appsettings.json.

Controller.cs

 private readonly IConfiguration _configuration;
 public Controller(IConfiguration configuration)
 {
     _configuration = configuration;
 }
 
 public void methodOne() 
 {
      string directory = _configuration.GetValue<string>("section:value");
 }

ControllerTest.cs

public class ControllerTest: ControllerTestsBase<Controller>
{

   public ControllerTest()
   {
      var builder = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json");
      Configuration = builder.Build();
   }

   [Fact]
   public void TestOne()
   {
       Controller.methodOne();
   }
}

When I debug and trace to the Controller.cs methodOne, the _configuration keeps prompted null error.

  • Apologies for the snippet of code, I have updated the code again.
rosepalette
  • 186
  • 2
  • 19
  • 1
    This code won't even compile. You can't call a member of a class like `methodOne()` simply by specifying its name. You'd have to create an instance of the controller somewhere. Please post an actual *complete* example that demonstrates the problem. – Panagiotis Kanavos Jun 30 '20 at 16:11
  • As for mocking - what exactly are you trying to mock? `IConfiguration` is an interface that can pull settings from *everywhere*, including [in-memory dictionaries](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#memory-configuration-provider). If you don't want to use a JSON file (there's nothing special about appsettings.json) use an in-memory source, or mock the interface directly – Panagiotis Kanavos Jun 30 '20 at 16:14

1 Answers1

0

Hey I've accomplished it by creating a Mock of the IConfiguration

private readonly Controller _controller;

public ControllerTest()
{
    // Create a mock if the IConfiguration object
    Mock<IConfiguration> configuration = new Mock<IConfiguration>();
    // Set it up to return whatever you want it returns back
    configuration.Setup(c => c.GetSection(It.IsAny<string>())).Returns("myDirectoryPath");
    // initialize your controller passing the mock object 
    _controller = new Controller(configuration.Object);
}

something like that would work. You create the mock of the Configuration you need. Create an instance of the controller you want to test, and pass there the Mock object you created, so it will get the values. Then you can call your test method like this:

[Fact]
public void TestOne()
{
    _controller.methodOne();
}
Herberth Gomez
  • 187
  • 1
  • 2
  • 19