I am using xUnit tool to write unit test cases in Dot net core. Here in this example, I am also trying to mock protected method of the controller.
public interface ITestService {
string GetString(string testString);
}
public class TestModel {
string testValue { get; set; }
}
public class TestController : Controller
{
readonly ITestService testService;
public TestController() {
}
public TestController(ITestService _testService) {
testService = _testService;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]TestModel testModel)
{
string test = GetString("testNew");
await Task.Run(() => "test");
return Ok(test);
}
protected virtual string GetString(string testString)
{
return "test" + testString;
}
}
Therefore, I will need to mock the controller itself to get protected method unit tested in its calling method.
But I am getting Null value when I call controller's method using Mocked object.
public class TestControllerTest
{
private Mock<ITestService> MockTestService { get; }
TestController controller { get; }
public TestControllerTest()
{
MockTestService = new Mock<ITestService>();
controller = new TestController(MockTestService.Object);
}
[Fact]
public void Post_TakesTestString_ReturnsString()
{
var MockController = new Mock<TestController>(MockTestService.Object);
MockController.Protected().Setup<string>("GetString", ItExpr.IsAny<string>()).Returns("testMockValue").Verifiable();
var result = MockController.Object.Post(new TestModel() { }).Result;
// result returns NULL value
MockController.Protected().Verify("GetString", Times.Once(), ItExpr.IsAny<string>());
}
}
My issue is on below line in code -
var result = MockController.Object.Post(new TestModel() { }).Result;
Which returns Null value, I expect, line should return OkObjectResult
with test string.