首页 > 解决方案 > Xunit 测试和 MOQ IActionResult 返回类型

问题描述

这是我正在测试的控制器功能......

   [HttpPost]
    public IActionResult Send([FromBody] MessageViewModel messageViewModel)
    {
        try
        {
            if (ModelState.IsValid)
            {
                var recipients = messageViewModel.To.Select(p => new Recipient { MobileNumber = p.MobileNumber, EmailAddress = p.EmailAddress });

                Message message = new Message
                {
                    To = recipients,
                    Subject = messageViewModel.Subject,
                    Body = messageViewModel.Body
                };

                var result = this.notifications.Send(message);

                if(result)
                {
                    this.logger.LogInformation(LoggingEvents.SendItem, $"Item with subject {messageViewModel.Subject} has been sent");
                    return this.Ok(result);
                }
                else
                {
                    this.logger.LogError(LoggingEvents.SendItemFail, $"Failure to send the item with subject {messageViewModel.Subject}");
                    return BadRequest();
                }
            }
            else
            {
                this.logger.LogError(LoggingEvents.SendItemFail, $"Invalid input. Fail to send the item with subject {messageViewModel.Subject}");
                return BadRequest();
            }
        }
        catch (Exception ex)
        {
            this.logger.LogError(LoggingEvents.SendItemFail, $"Something went wrong: {ex}");
            return this.StatusCode(StatusCodes.Status500InternalServerError);
        }
    }

这是我的 xunit 测试代码。

    public class Send
    {
        [Fact]
        public void Should_ReturnOk_When_To_PropertyIsNull()
        {
            var mock_notificationsController = new Mock<NotificationsController>();

            mock_notificationsController
                .Setup(m => m.Send(It.IsAny<MessageViewModel>()))
                .Returns();


        }

        public MessageViewModel GetMessageViewModel()
        {
            List<RecipientViewModel> recipients = new List<RecipientViewModel>();
            recipients.AddRange(new[]
            {
                new RecipientViewModel
                {
                    EmailAddress = "randomdummysender16",
                    MobileNumber = "639292820947"
                },
            });

            var message = new MessageViewModel()
            {
                To = recipients,
                Subject = "Test Subject",
                Body = null
            };

            return message;
        }
    }

我不知道要返回什么,我正在输入 BadRequestResult 但它说“BadRequestResult”是一种类型,在给定的上下文中无效。

我似乎找不到可靠的文档或指导如何对您的控制器进行单元测试,有人有来源吗?

标签: c#asp.net-coremoqxunit

解决方案


推荐阅读