gpt4 book ai didi

c# - 单元测试中 Web Api Controller 的 ContentResult 总是返回 null

转载 作者:行者123 更新时间:2023-11-30 22:53:07 25 4
gpt4 key购买 nike

我尝试在 getMethod(string id) 的单元测试中检查的 ContentResult 始终返回 null。 Controller 调用的服务返回 DTO 模型。

我试过了 Action 结果为 OkNegotiatedContentResult Action 结果为 OkNegotiatedContentResult

单元测试:

      [TestMethod]
public void GetUserInformation_ReturnsUserDetails()
{
//Arrange
UserDetails userDetails = new UserDetails();
mockUserService.Setup(x =>
x.GetuserInformation(It.IsAny<string>
())).Returns(userDetails);
//Act
IHttpActionResult result =
userController.GetUserInformation("226");
var contentResult = result as
OkNegotiatedContentResult<UserDetails>;
//Assert
//Validate Ok Result
Assert.IsNotNull(contentResult);//this fails
Assert.IsNotNull(contentResult.Content);
Assert.AreEqual("226", contentResult.Content.userID);
Assert.IsInstanceOfType(result,
typeof(OkNegotiatedContentResult<UserDetails>));//this assert works

}

Controller :

public IHttpActionResult GetUserInformation(string userID)
{
if (!string.IsNullOrEmpty(userID))
{
var result = _userService.GetUserInformation(userID);
if (result != null)
{
return Ok(result);
}
return InternalServerError();
}
else
{
return BadRequest("User Not Found");
}
}

服务层:

 public UserDetails GetUserInformation(string userID)
{
UserDetails userDetails = new UserDetails();
//business logic
return userDetails;
}

ContentNegotiator = '((System.Web.Http.Results.OkNegotiatedContentResult)result).ContentNegotiator' 抛出类型为'System.InvalidOperationException'的异常

Request = '(result as OkNegotiatedContentResult).Request' 抛出了 'System.InvalidOperationException' 类型的异常

最佳答案

构建 API 应用程序可能有不同的方法。

我的方法是 API 应该构建为 3 层:

  • 表示层: Controller
  • 业务逻辑:服务
  • 数据层:存储库

Controller 和存储库应尽可能精简。所有的逻辑都应该在服务层。在这种情况下,应用程序将是可维护、可扩展和可测试的。

测试示例

使用的包:

  • NUnit
  • NUnit3TestAdapter
  • 起订量

您还可以使用:

  • FluentAssertions
  • AutoFixture.NUnit3

服务的测试类示例:

[TestFixture]
public class OrdersServiceTests
{
private OrdersService _sut;

private Mock<ICapacityService> _capacityService;

private Mock<IOrdersRepository> _ordersRepository;

[SetUp]
public void Setup()
{
// Executed for each test. Mocks are recreated. Tests are not influencing each other.

_ordersRepository = new Mock<IOrdersRepository>();
_capacityService = new Mock<ICapacityService>();

_sut = new OrdersService(_ordersRepository.Object, _capacityService.Object);
}

[Test]
public async Task Should_CheckCapacity_WhenCreatingOrder()
{
//// Arrange

var orderEntity = new OrderEntity
{
Id = Guid.NewGuid(),
};

//// Act

await _sut.CreateAsync(orderEntity);

//// Assert

_capacityService
.Verify(
x => x.CheckCapacity(
It.Is<Guid>(g => g.Equals(orderEntity.Id)))),
Times.Once);
}
}

关于c# - 单元测试中 Web Api Controller 的 ContentResult 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57597861/

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