Am writing unit test cases (MSTest) for a webAPI method.
- Do I have to directly create a new instance of the controller and call the webAPI method to obtain the response? & then keep an Assert statement to check if the value inside the response matches with a value? or
- Do I have to create an interface for the controller and then mock the controller class and the input values and call the webAPI method to obtain the response? & then keep an Assert statement to check if the value inside the response matches with a value?
If so how to create an interface of the controller and create mock of the same? (ex: controller name: ABCController , API Method to call : ABCGet() )
Tuhin PaulPosted Feb 28, 2023, 2:27 AM
Hi Aruna,
When writing unit tests for a web API method, it is recommended to create an interface for the controller and then mock the controller class and input values. This approach allows you to isolate the unit under test from external dependencies and focus solely on testing the behavior of the method.
To create an interface for a controller, you can define an interface with the same method signatures as the controller. For example, if your controller is named ABCController and the API method you want to test is named ABCGet(), you can create an interface as follows:
Next, you can create a mock of the interface using a mocking framework such as Moq. Here's an example of how to create a mock of the IABCController interface using Moq:
Once you have created the mock controller, you can set up the behavior of the ABCGet() method using the Setup() method provided by Moq:
Finally, you can call the ABCGet() method on the mock controller and assert on the response to verify that the method behaves as expected:
By mocking the controller and input values, you can test the behavior of the API method in isolation and verify that it returns the expected results for different inputs and scenarios.
Rajeesh MenothPosted Feb 27, 2023, 1:56 PM
Hi,
Any how mock is required and better to go through Microsoft documentation.
https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-mstest