0

I have a controller and I need to unit test it. The controller defines the following constructor:

public class ControllerName : AnotherController
{
    public ControllerName(
        IWebHostEnvironment environment,
        ILogger<ControllerName> logger,
        IHttpContextAccessor httpContext) 
        : base(environment, logger, httpContext)
    {
    }

    ...
}

The Controller inherit AnotherController, who sets:

public readonly IWebHostEnvironment _environment;
public readonly ILogger _logger;
public readonly IHttpContextAccessor _httpContext;
    
public AnotherController(
    IWebHostEnvironment environment,
    ILogger<AnotherController> logger,
    IHttpContextAccessor httpContext)
{
    _logger = logger;
    _environment = environment;
    _httpContext = httpContext;
    
    if (_httpContext == null)
        throw new NullReferenceException("_httpContext -> NullReferenceException");
}

The two controllers are in different projects.

I've searched and couldn't find a way to instantiate the first controller in my test class because of the Dependency Injection.

Does anyone know how to do it?

I'm using .NET 5.

Steven
  • 159,023
  • 23
  • 313
  • 420
Murilo
  • 1
  • 1
  • Which testing framework? – Ermiya Eskandary Oct 11 '21 at 19:33
  • You need to add reference of both projects – vivek nuna Oct 11 '21 at 19:59
  • 2
    Can you elaborate on what is blocking you from instantiating the first Controller in your Test Class? Why doesn't something `new ControllerName(new FakeWebHostEnvironment(), new FakeLogger(), new FakeHttpContextAccessor())` not work? – Steven Oct 12 '21 at 07:51
  • 2
    Note, there are many questions about DI i.c.w. unit testing here on Stack Overflow, such as [this](https://stackoverflow.com/questions/37724738/how-to-unit-test-asp-net-core-application-with-constructor-dependency-injection) and [this](https://stackoverflow.com/questions/56521382/unit-testing-the-dependency-injection/56523604) (but a quick search finds many others) that could help you understand how to unit test classes that apply DI patterns. – Steven Oct 12 '21 at 07:53

0 Answers0