Using IOptions class in .Net Core Unit Testing.

When implementing unit testng for a interface that was using a IOptions class, we were getting an null exception when trying to access the value using _mockMyconfig!.Object.Value. To resolve this error this, you have to manually create the MyConfig class and then assign it to the Value property.
MyConfig myConfig = new MyConfig() { BaseURL = "https://mocktest.com" };
_mockMyconfig = new Mock>(MockBehavior.Loose);
// We need to set the Value of IOptions to be the Myconfig Class, if this step is not done, then we get null exception when we try to use the value like this _mockMyconfig!.Object.Value
_mockMyconfig.Setup(ap => ap.Value).Returns(myConfig); Once you have done this, then we use this in the unit testing like without getting the null exception.
_mockHttpClient!.Setup(repo => repo.GetPWSHttpClient(_mockMyconfig!.Object.Value)).Returns(new HttpClient()).Verifiable();
The Main NuGet packages that have been used for this test are
1. Microsoft.NET.Test.Sdk: 17.9.0
2. Moq: 4.20.70
3. NUnit:4.0.1

Comments

Popular posts from this blog

Print from WPF using ReportViewer Control

Printing SSRS 2008 R2 Reports from C#.