2
votes

I want to write a unit test case of .net core MVC controller. Controller calls the .net core API.

I am able to mock the IHttpHelper but it returns always null. I have my IHttpHelper

public interface IHttpHelper
{
    Task<HttpResponseMessage> GetAsync(string apiUrl);

    Task<HttpResponseMessage> PutAsync(string apiUrl, HttpContent content);

    Task<HttpResponseMessage> PostAsync(string apiUrl, HttpContent content);

    Task<HttpResponseMessage> DeleteAsync(string apiUrl);
}

My Web API code is

public class ClientTransferController : Controller
{
    private readonly CTUClientTransferProxy _searchProxy;

    private readonly IClientBLL _clientBll;

    public ClientTransferController(IConfiguration configuration) : this(configuration, new ClientBLL(configuration), new WcfServiceHelper())
    {
        _searchProxy = new CTUClientTransferProxy(configuration, new WcfServiceHelper());
    }


    public ClientTransferController(IConfiguration configuration, IClientBLL clientBll, IWcfServiceHelper wcfServiceHelper)
    {
        _clientBll = clientBll;
    }

    [Route("api/wcfctu/validatesitecodes")]
    public async Task<clsCTUValidateSiteCodesResults> ValidateSiteCodes([FromForm]string sourceSiteCode, [FromForm]string targetSiteCode)
    {
        var result = await _searchProxy.ValidateSiteCodesAsync(new clsCTUValidateSiteCodesCriteria { SourceSiteCode = sourceSiteCode, TargetSiteCode = targetSiteCode });
        return result;
    }
}

And I am calling above API through my MVC controller

public class FirmAdminController : Controller
{
    private readonly IHttpHelper _httpHelper;

    public FirmAdminController(IHttpHelper httpHelper)
    {
        _httpHelper = httpHelper;
    }

    public async Task<IActionResult> ValidateSiteCodes(SiteCodeInputsViewModel siteCodeInputs)
    {

        if (ModelState.IsValid)
        {
            var values = new Dictionary<string, string>
            {
                {"sourceSiteCode", siteCodeInputs.SourceSiteCode.Sitecode},
                {"targetSiteCode", siteCodeInputs.TargetSiteCode.Sitecode}
            };
            var content = new FormUrlEncodedContent(values);

            var clientTransferValoidateSiteCodesApiUrl = $"api/wcfctu/validatesitecodes";
            HttpResponseMessage response = await _httpHelper.PostAsync(clientTransferValoidateSiteCodesApiUrl, content);

            if (response.IsSuccessStatusCode)
            {
                var jsonData = response.Content.ReadAsStringAsync().Result;
                return Ok(jsonData);
            }
        }
        return Json(null);
    }
}

I want to write unit test cases for ValidateSiteCodes of ClientTransferController .

Below is my test case

public class FirmAdminControllerTests
{
    private  FirmAdminController _controller;
    private readonly Mock<IHttpHelper> _mockHttpHelper;
    public FirmAdminControllerTests()
    {
        _mockHttpHelper = new Mock<IHttpHelper>();
        _controller = new FirmAdminController(_mockHttpHelper.Object);
    }

    [Fact]
    public void ValidateSiteCodes_IfValid()
    {
        //Arrange
        var clientTransferValoidateSiteCodesApiUrl = "api/wcfctu/validatesitecodes";
        SiteCodeInputsViewModel siteCodeInputsViewModel = new SiteCodeInputsViewModel
        {
            SourceSiteCode = new SiteCodeInput { Sitecode = "Bravouat" },
            TargetSiteCode = new SiteCodeInput { Sitecode = "CUAT" }
        };
        var values = new Dictionary<string, string>
        {
            {"sourceSiteCode", siteCodeInputsViewModel.SourceSiteCode.Sitecode},
            {"targetSiteCode", siteCodeInputsViewModel.TargetSiteCode.Sitecode}
        };

        clsCTUValidateSiteCodesResults result1 = new clsCTUValidateSiteCodesResults
        {
            Success = true
        };

        var headerDictionary = new HeaderDictionary();
        var response = new Mock<HttpResponse>();
        response.SetupGet(r => r.Headers).Returns(headerDictionary);
        var httpContext = new Mock<HttpContext>();
        httpContext.SetupGet(a => a.Response).Returns(response.Object);



        var myContent = JsonConvert.SerializeObject(result1);
        var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
        var byteContent = new ByteArrayContent(buffer);
        byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        HttpResponseMessage responseMessage = new HttpResponseMessage
        {
            Content = byteContent,
            StatusCode = HttpStatusCode.OK
        };

        var content = new FormUrlEncodedContent(values);   

        _mockHttpHelper.Setup(c => c.PostAsync(clientTransferValoidateSiteCodesApiUrl, content))
            .Returns(async () => { await Task.Yield();
                return responseMessage;
            });

        //Act
        var result = _controller.ValidateSiteCodes(siteCodeInputsViewModel);

        // Assert

        var viewResult = Assert.IsType<ViewResult>(result);

    }   
}

But

_mockHttpHelper.Setup(c => c.PostAsync(clientTransferValoidateSiteCodesApiUrl, content))
                .Returns(async () => { await Task.Yield();
                    return responseMessage;
                });

does not return the HttpResponseMessage. It returns null and that is why my test case is getting fail.

1
Why are you using async () => { await Task.Yield();? That's not only useless, the async lambda is most likely the problem. Just use () => responseMessage or if required () => Task.FromResult(responseMessage) - Camilo Terevinto
I have tried () => Task.FromResult(responseMessage) also but I am getting same result. - Sharad Singh

1 Answers

2
votes

The test is failing for many reasons.

The controller under test is mixing async and blocking calls like .Result,

var jsonData = response.Content.ReadAsStringAsync().Result;

which can lead to deadlocks

Reference Async/Await - Best Practices in Asynchronous Programming

The action should be async all the way through

public async Task<IActionResult> ValidateSiteCodes(SiteCodeInputsViewModel siteCodeInputs) {
    if (ModelState.IsValid) {
        var values = new Dictionary<string, string> {
            {"sourceSiteCode", siteCodeInputs.SourceSiteCode.Sitecode},
            {"targetSiteCode", siteCodeInputs.TargetSiteCode.Sitecode}
        };
        var content = new FormUrlEncodedContent(values);

        var clientTransferValoidateSiteCodesApiUrl = $"api/wcfctu/validatesitecodes";
        HttpResponseMessage response = await _httpHelper.PostAsync(clientTransferValoidateSiteCodesApiUrl, content);

        if (response.IsSuccessStatusCode) {
            var jsonData = await response.Content.ReadAsStringAsync();
            return Ok(jsonData);
        }
    }
    return BadRequest(ModelState);
}

Now on to the test. The post setup is being over complicated with the expected arguments and the way the response is being returned.

Moq has a ReturnsAsync to allow for mocked async flows to complete as expected.

_mockHttpHelper
    .Setup(_ => _.PostAsync(It.IsAny<string>(), It.IsAny<HttpContent>()))
    .ReturnsAsync(responseMessage);

In keeping this async, the test method should be made async as well.

[Fact]
public async Task ValidateSiteCodes_IfValid() {
    //...
}

And await the method under test.

//Act
var result = await _controller.ValidateSiteCodes(siteCodeInputsViewModel);