-2

我创建了一种小型 xunit 测试用例,但我不知道如何创建我在下面提到的这个控制器。

    public class PropertyController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<PropertyController> _logger;

        public PropertyController(IMediator mediator, ILogger<PropertyController> logger)
        {
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }
        public async Task<IActionResult> AddProperty([FromBody] AddPropertyCommand command)
        {
            bool commandResult = false;
            _logger.LogInformation(
                "----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})",
                command.GetGenericTypeName(),
                nameof(command.ModifiedUserId),
                command.ModifiedUserId,
                command);
            commandResult = await _mediator.Send(command);
            if (!commandResult)
            {
                return BadRequest();
            }
            return Ok();
        }

我创造了这样的。我已经模拟了依赖项并为 add 命令创建了一个测试用例是否工作正常

public class PropertyControllerTest
    {
        private readonly PropertyController _it;
        private readonly Mock<IMediator> _mediatorMock;
        private readonly Mock<ILogger<PropertyController>> _loggerPropertycontrollerMock;

        public PropertyControllerTest()
        {
            _mediatorMock = new Mock<IMediator>();
            _loggerPropertycontrollerMock = new Mock<ILogger<PropertyController>>();
            _it = new PropertyController(_mediatorMock.Object, _loggerPropertycontrollerMock.Object);
        }
        [Fact]
        public void it_Should_add_information_successfully_and_returns_200_status_result()
        {
            //How can i write xunit test case. I'm creating like this
            _mediatorMock.Setup(x => x.Send().Returns(property);   
        }
4

1 回答 1

0

下面的测试涵盖了 200 状态结果 - 对错误请求的类似测试将非常相似。

[Fact]
public void it_Should_add_information_successfully_and_returns_200_status_result()
{
    // Arrange
    var expected = new AddPropertyCommand();
    _mediatorMock.Setup(x => x.Send(It.IsAny<AddPropertyCommand>())).Returns(true);

    // Act
    var actionResult = _it.AddProperty(expected);

    // Assert
    actionResult.ShouldBeAssignableTo<OkResult>();

    _mediatorMock.Verify(x => x.Send(expected));
}

NBactionResult.ShouldBeAssignableTo<OkResult>();是使用 Shouldly 断言框架编写的,您可以将其换成您喜欢的任何东西。XUnit 中内置的内容是这样的:Assert.IsType(typeof(OkResult), actionResult);

于 2019-06-17T12:52:59.900 回答