Asp.Net Core 2.1 ApiController不会在单元测试下自动验证模型

时间:2018-07-26 16:48:13

标签: c# unit-testing asp.net-core-2.1

我正在使用xUnit对返回ActionResult<T>的ASP.NET Core 2.1控制器方法进行单元测试。控制器类装饰有[ApiController]属性,以便该方法在实时运行时自动执行模型验证。但是,控制器方法不会在我的单元测试中自动触发模型验证,因此我不知道为什么。

这是我的单元测试

[Fact]
public async Task post_returns_400_when_model_is_invalid()
{
    // arrange
    var mockHttpClientFactory = new Mock<IHttpClientFactory>();
    var mockHttpMessageHandler = new Mock<FakeHttpMessageHandler> {CallBase = true};
    mockHttpMessageHandler.Setup(mock => mock.Send(It.IsAny<HttpRequestMessage>()))
        .Returns(new HttpResponseMessage(HttpStatusCode.Accepted)
        {
            Content = new StringContent("{\"response\": {\"numFound\": 0, \"start\": 0, \"docs\": []}}")
        });
    var httpClient =
        new HttpClient(mockHttpMessageHandler.Object)
        {
            BaseAddress = new Uri("http://localhost:8983/"),
            DefaultRequestHeaders = {{"Accept", "application/json"}}
        };
    mockHttpClientFactory.Setup(mock => mock.CreateClient("SolrApi")).Returns(httpClient);
    var slackOptions = Options.Create<SlackOptions>(new SlackOptions());
    var prdSolrService = new PrdSolrService(Options.Create<PrdOptions>(new PrdOptions()));
    var slackMessageService = new PrdSlackMessageService(new HtmlTransformService(), slackOptions);
    var controller = new SlackPrdController(slackOptions, mockHttpClientFactory.Object, prdSolrService, slackMessageService);
    var slackRequest = new SlackRequest();

    // act
    var sut = await controller.Post(slackRequest);

    // assert 
    // note: validation should fail and not return a SlackMessage, but validation is not firing
    // auto-validation is part of [ApiController] attribute on the Controller class
    Assert.IsType<BadRequestObjectResult>(sut.Result);
}

这是正在测试的 Controller 方法。

[HttpPost]
public async Task<ActionResult<SlackMessage>> Post(SlackRequest request)
{
    if (request.Token != _slackOptions.Token)
    {
        ModelState.AddModelError("Token", "Invalid verification token.");
        return BadRequest(ModelState);
    }

    var solrUri = _solrService.SlackRequestToSolrUri(request);
    var client = _httpClientFactory.CreateClient("SolrApi");
    var raw = await client.GetStringAsync(solrUri);
    var response = _solrService.ParseSolrResponse(raw);
    var slackMessage = _slackMessageService.InitialMessage(response);

    return slackMessage;
}

这是 SlackRequest模型,其中需要Token属性。

public class SlackRequest
{
    public SlackRequest() {}

    [JsonProperty("token")]
    [Required]
    public string Token { get; set; }

    [JsonProperty("team_id")]
    public string TeamId { get; set; }

    [JsonProperty("team_domain")]
    public string TeamDomain { get;set; }

    [JsonProperty("enterprise_id")]
    public string EnterpriseId { get; set; }

    [JsonProperty("enterprise_name")]
    public string EnterpriseName { get; set; }

    [JsonProperty("channel_id")]
    public string ChannelId { get; set; }

    [JsonProperty("channel_name")]
    public string ChannelName { get; set; }

    [JsonProperty("user_id")]
    public string UserId { get; set; }

    [JsonProperty("user_name")]
    public string UserName { get; set; }

    [JsonProperty("command")]
    public string Command { get;set; }

    [JsonProperty("text")]
    public string Text { get; set; }

    [Url]
    [JsonProperty("response_url")]
    public string ResponseUrl { get; set; }

    [JsonProperty("trigger_id")]
    public string TriggerId { get; set; }
}

1 个答案:

答案 0 :(得分:1)

  

控制器类装饰有[ApiController]属性,因此该方法在实时运行时会自动执行模型验证。但是,控制器方法不会在我的单元测试中自动触发模型验证,因此我不知道为什么。

ApiControllerAttribute是仅在基础结构运行时才相关的元数据,因此这意味着您将必须在集成测试中使用TestServer并实际请求接受测试的操作才能使它成为测试的一部分,并得到框架的认可。

这是因为随着请求通过基础结构,该属性基本上标记了控制器/动作,以使动作过滤器(ModelStateInvalidFilter)检查模型并更新请求的模型状态。如果发现模型无效,则会使请求短路,甚至无法达到要调用的动作。