0

I have a controller in my asp.net core 2.1 project which has IOptions<RaygunSettings> as constructor parameter.

Dependency Injection is added in Startup.cs as shown below.

services.AddRaygun(Configuration);

Everything works fine when you run the web application. But when It didn't work for xunit project.

SampleController.cs

private readonly RaygunClient raygunClient;
public SampleController(IOptions<RaygunSettings> settings)
{
    _settings = settings;
    raygunClient = new RaygunClient(_settings.Value);
}

private Mock<IOptions<RaygunSettings>> _settings;

SampleControllerTest.cs

public SampleControllerTest()
{
    //Arrange
    _settings = new Mock<IOptions<RaygunSettings>>();
     _controller = new SampleController(_settings.Object);
}

Above code explains how my SampleController and SampleControllerTest constructor looks like.

When I try to run the xunit test at the raygunclient instantiation time I'm getting

Object reference not set to an instance of an object

How to fix this issue in xunit test project for asp.net core 2.1

Suvethan Nantha
  • 2,404
  • 16
  • 28
  • The question I have to ask is: what's null? – ProgrammingLlama Sep 27 '18 at 06:39
  • Raygunsettings value is null – Suvethan Nantha Sep 27 '18 at 06:40
  • Do you mean `_settings.Value`? or `settings`? If you mean `_settings.Value`, it's because you didn't mock it, I believe. All your `SampleControllerTest` code does it create a mock of `IOptions` without mocking any of the methods/properties. – ProgrammingLlama Sep 27 '18 at 06:40
  • yes @John _settings.Value is null. Moreover I don't know how to pass dependency injection to controller from controllerTest since I don't have a startup.cs in my xunit test project – Suvethan Nantha Sep 27 '18 at 06:43
  • You created a dummy/mocked object `_settings`. You should also implement what `_settings.Value` should return. – Ilian Sep 27 '18 at 07:00
  • _settings.Value returns null @ilian-pinzon – Suvethan Nantha Sep 27 '18 at 07:27
  • It returns null because *you* have to supply its value. You created `_settings` (via the mock), you should also implement what `_settings.Value` returns. I don't mean to be rude but is this your first time using mocks? I think you are using Moq? If so, it will be helpful to understand how mocking and Moq works first. Look at how to mock [properties](https://github.com/Moq/moq4/wiki/Quickstart#properties) especially. You need to do something like `_settings.Setup(s=> s.Value).Returns(/* your object here */);` – Ilian Sep 27 '18 at 07:37
  • @ilian-pinzon yes it is my first time using mocks. ya sure will check documentation first. – Suvethan Nantha Sep 27 '18 at 08:03

0 Answers0