为什么此控制器操作的结果为null?

时间:2017-07-19 16:07:42

标签: c# unit-testing asp.net-web-api moq xunit

我从头开始一个新项目。目前,我正在设计一些元素,并尝试尽早实施单元测试。问题是,单元测试失败是由于控制器动作的响应似乎是空的。在监视窗口中,actionResult显示"表达式评估程序中的内部错误"并且contentResult为空。

我该如何解决这个问题?

xunit 2.2.0.3545,Moq 4.7.63.0

这是单元测试(xunit):

// Used in the unit tests
private List<City> cities = new List<City>
{
 new City { City_Name = "Chicago", City_Code = 1 },
 new City { City_Name = "New York", City_Code = 2 },
 new City { City_Name = "Seattle", City_Code = 3 }
};

[Fact]
public async Task Get_AllCities_PropertiesArePopulated()
{
    // Arrange
    var mockService = new Mock<ICityService>();
    mockService.Setup(x => x.GetCities()).ReturnsAsync(this.cities);

    var controller = new CityController(mockService.Object);

    // Act
    IHttpActionResult actionResult = await controller.GetCities();
    var contentResult = actionResult as OkNegotiatedContentResult<List<City>>;

    foreach (var city in contentResult.Content)
    {
        // doesn't get here due to .Content being null.
    }
}

这是我的控制器:

public class CityController : ApiController
{
    private readonly ICityService cityService;

    public CityController(ICityService svc)
    {
        this.cityService = svc;
    }

    public async Task<IHttpActionResult> GetCities()
    {
        var cities = await this.cityService.GetCities();

        if (!cities.Any())
        {
            return this.BadRequest();
        }

        return this.Ok(cities);
    }
}

服务界面:

public interface ICityService
{
    Task<IEnumerable<City>> GetCities();
}

1 个答案:

答案 0 :(得分:3)

seed返回GetCities

IEnumerable<City>

但是在测试的演员表中,您使用Task<IEnumerable<City>> GetCities();

将其强制转换为错误的类型
List<City>

何时使用var contentResult = actionResult as OkNegotiatedContentResult<List<City>>;

IEnumerable<City>