简体   繁体   中英

ASP.NET Web API Unit Testing - Read Json string from controller returning JsonResult

I have a controller method which returns JsonResult (Namespace: System.Web.Http.Results )

        public async Task<IHttpActionResult> GetConfig(string section, string group, string name)
        {
            var configurations = await _repository.GetConfig(section, group, name);
            return Json(new { configurations = configurations.ToList() }, SerializerSettings);
        }

I am trying to Unit Test this method.Here is what I have so far

        [Test]
        public async void Should_Return_List_Of_Configs_Json()
        {
            var section= "ABC";
            var group= "some group";
            var name= "XYZ";
            var response =  await controller.GetConfig(section, group, name);
            Assert.IsNotNull(response);

        }

I am not able to read Json string from the above method as I can't see a response.Content property.The call to the method is returning mocked response.

Can someone help me out with this?

If I understood correctly you need something like this ( source ):

var response = await controller.GetConfig(section, group, name);
var message = await response.ExecuteAsync(CancellationToken.None);
var content = await message.Content.ReadAsStringAsync();
Assert.AreEqual("expected value", content);

You can just cast the IHttpActionResult to the appropriate JsonResult in you unit test. The anonymous type you are using in you example should be replaced by a DTO type, so you can properly cast it in the unit test. Something like this should do it

    [Test]
    public async void Should_Return_List_Of_Configs_Json()
    {
        var section= "ABC";
        var group= "some group";
        var name= "XYZ";
        var response =  (JsonResult<List<YourDtoType>>)await controller.GetConfig(section, group, name);
        Assert.IsNotNull(response);

    }

The second possibility is returning the actual type from the Api Controller instead of the IHttpActionResult. Like that

    public async Task<List<YourDtoType>> GetConfig(string section, string group, string name)
    {
        var configurations = await _repository.GetConfig(section, group, name);
        return configurations.ToList();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM