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() )

Rajeesh MenothRank #118 · 18.4K reputationPosted Feb 27, 2023, 8:56 AM EST
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
Tuhin PaulRank #7 · 71.9K reputationPosted Feb 27, 2023, 9:27 PM EST
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:
public interface IABCController { ActionResult ABCGet(); }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:
var mockController = new Mock();Once you have created the mock controller, you can set up the behavior of the ABCGet() method using the Setup() method provided by Moq:
mockController.Setup(c => c.ABCGet()).Returns(new ActionResult());Finally, you can call the ABCGet() method on the mock controller and assert on the response to verify that the method behaves as expected:
var result = mockController.Object.ABCGet(); Assert.IsNotNull(result);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.