如何测试以匿名类型返回Task <ihttpactionresult>的控制器方法

时间:2017-03-10 11:27:07

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

我有一个Web API控制器方法,如下面给出的SessionId类型为'string'

[HttpPost]
[Route("init")]
[ApiMeter("search_init")]
public async Task<IHttpActionResult> InitiateAsync(SearchInitRequest query,
    CancellationToken cancellationToken)
{
    Validations.EnsureValid(query, new SearchRequestValidator());
    string sessionId = await Service.InitiateSearchAsync(query, cancellationToken);
    return Ok(new { sessionId });
}

我有下面的测试用例

[Fact]
public void GetSearchInit_Success_Valid()
{
    var mockCarService = new Mock<ICarService>();

    using (new AmbientContextScope(GetCarCallContext()))
    {
        var request = Data.DataProvider.TestDataProvider.GetJsonResult<CarSearchInitRequest>(
       SearchInitScenarioRequests.CarSearchInitSuccess);
        var response = Data.DataProvider.TestDataProvider.GetResponse<CarSearchInitResponse>(
       SearchInitScenarioResponse.CarSearchInitSuccess);

        mockCarService.Setup(f => f.InitiateSearchAsync(request, CancellationToken.None))
            .Returns(Task.FromResult(response.SessionId));

        SearchController controller = new SearchController(mockCarService.Object);
        var result = controller.InitiateAsync(request, CancellationToken.None).Result;
        var status = result as OkNegotiatedContentResult<string>;
        Assert.NotNull(status.Content);

    }
}

在此测试案例中,我的状态为null。虽然在调试时我可以看到SessionId内有status.Content属性但由于这是匿名类型,我无法读取该值。

我也试过

var status = result as OkNegotiatedContentResult<object>;

仍然没有运气

1 个答案:

答案 0 :(得分:0)

这是一个关于如何处理测试操作的最小完整示例。然而,这更像是一个集成测试,因为它正在通过框架功能来访问结果的内容。

[TestClass]
public class UnitTest6 {
    [TestMethod]
    public async Task Action_Returns_AnonymousTypeResult() {
        //Arrange
        var controller = new SearchController() {
            Configuration = new HttpConfiguration(),
            Request = new HttpRequestMessage()
        };
        var expected = "hello world";

        //Act
        var result = await controller.InitiateAsync();
        var response = await result.ExecuteAsync(CancellationToken.None);
        var status = await response.Content.ReadAsAsync<dynamic>();

        //Assert
        Assert.IsNotNull(status.sessionId);
        Assert.AreEqual(expected, status.sessionId);
    }

    [Authorize]
    public class SearchController : ApiController {
        [HttpPost]
        public async Task<IHttpActionResult> InitiateAsync() {
            string sessionId = await Task.FromResult("hello world");
            return Ok(new { sessionId });
        }
    }
}

通过执行结果来获取响应消息,现在可以访问响应的内容。允许将内容解析为dynamic,以便可以访问成员。