2

Hi I am writing unit test cases for the following method in my controller.

    [HttpGet]
    [Route("GetList")]
    public IHttpActionResult GetAllMasterList()
    {
        var MasterList = _masterListRepo.GetAll().Select(t => new { t.MASTER_ID, t.MASTER_NAME }).OrderBy(t=>t.MASTER_NAME).ToList();
        return Ok(MasterList);
    }

For the above method the unit test case method is as follows.

    [TestMethod]
    public void AllMastersList()
    {
        //Arrange
        var controller = new MastersController();
        var actualResults = _masterListRepo.GetAll().ToList();

        //Act
        var actionResult = controller.GetAllMasterList();

        //Assert
        Assert.IsTrue(actionResult.GetType().GetGenericTypeDefinition() == typeof(OkNegotiatedContentResult<>));
        var contentExpected = actionResult as OkNegotiatedContentResult<IEnumerable<dynamic>>;
        Assert.IsNotNull(contentExpected.Content.ToList());
        Assert.AreEqual(contentExpected.Content.Count(), actualResults.Count);

    }

I am getting contentExpected as null. How do I cast this Ok() result to get the value. How to do it?

1

1 Answer 1

2

I would strongly recommed against returning anonymous objects. Introduce a model class with will allow you to easily unit test you api calls.

public class Master {
    public string Id { get; set;}
    public string Name { get; set;}
}

var MasterList = _masterListRepo.GetAll().Select(t => new Master {Id = MASTER_ID, Name = t.MASTER_NAME).OrderBy(t=>t.MASTER_NAME).ToList();

Also you don't have to return an IHttpActionResult from your Method, you can just return an IEnumerable with also makes your test way more readable

var controller = new MastersController();
var actualResults = _masterListRepo.GetAll().ToList();

var resultsFromController = controller.GetAllMasterList(); //This is now an IEnumerable<Master>)
Sign up to request clarification or add additional context in comments.

1 Comment

totally got your point. But there must be some way to test such methods. Which returns anonymous lists.

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.