Search code examples
c#unit-testingtestingxunitservicetestcase

I want to Create Xunit test for this controller. How can i do that


I have created small kind of xunit test case but I don't know how to create this controller which i have mention below.

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

I have created like this. i have mock the dependency and create a test case for add command is working fine or not

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

Solution

  • The test below covers the 200 status result - a similar test for bad requests would be very similar.

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

    N.B. actionResult.ShouldBeAssignableTo<OkResult>(); is written using the Shouldly assertion framework, you can swap that out for anything you like. The one built into XUnit would be like this: Assert.IsType(typeof(OkResult), actionResult);