Posts

Showing posts from July, 2024

Creating a C# class from JSON.

Image
Previously to create a C# class from JSON, we would use some tool, either web based or otherwise to generate the C# class. Now we have an option to generate an C# class directly from Visual Studio using the menu option Edit --> Paste Special --> Paste JSON as Classes. Steps to implement this. 1. Copy the JSON that we to use to generate the C# class 2. Create a new C# class 2. Click on the menu option Edit --> Paste Special --> Paste JSON as Classes 3. We can see the C# class created. You might have to change some of the data types as at times, the date and integer properties are generated as string. Hope this helps.

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 th...