gpt4 book ai didi

c# - 如何测试以匿名类型返回 Task 的 Controller 方法

转载 作者:行者123 更新时间:2023-11-28 20:52:03 25 4
gpt4 key购买 nike

我有一个如下所示的 Web API Controller 方法 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。虽然在调试时我可以看到 status.Content 中有 SessionId 属性,但由于这是匿名类型,我无法读取该值。

我也试过

var status = result as OkNegotiatedContentResult<object>;

还是不行

最佳答案

这是一个最小的完整示例,说明如何解决测试操作的问题。然而,这更像是一个集成测试,因为它通过框架功能来访问结果的内容。

[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 });
}
}
}

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

关于c# - 如何测试以匿名类型返回 Task<IHttpActionResult> 的 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42717280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com