How to Unit Test with ActionResult?

后端 未结 3 824
-上瘾入骨i
-上瘾入骨i 2020-12-18 19:06

I have a xUnit test like:

[Fact]
public async void GetLocationsCountAsync_WhenCalled_ReturnsLocationsCount()
{
    _locationsService.Setup(s => s.GetLocat         


        
3条回答
  •  心在旅途
    2020-12-18 19:51

    The problem lies in the confusing interface of ActionResult that was never designed to be used by us humans. As stated in other answers, ActionResult has either its Result or Value property set but not both. When you return an OkObjectResult the framework populates the Result property. When you return an object the framework populates the Value property.

    I created the following simple helper for my test library to help me test the return values when I am using OkObjectResult Ok() or other results inheriting from ObjectResult

    private static T GetObjectResultContent(ActionResult result)
    {
        return (T) ((ObjectResult) result.Result).Value;
    }
    

    This lets me do the following:

    var actionResult = await controller.Get("foobar");
    Assert.IsType(actionResult.Result);
    var resultObject = GetObjectResultContent(actionResult);
    Assert.Equal("foobar", resultObject.Id);
    

提交回复
热议问题