0

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?

2 Answers 2

0

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.