c# - 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”是一种类型,在给定的上下文中无效。
我似乎找不到可靠的文档或指导如何对您的控制器进行单元测试,有人有来源吗?
解决方案
推荐阅读
- opnet - 为什么不能windef。OPNET能识别H文件吗?
- qt - 在构建主目标之前,Qmake 在阻塞主目标的同时构建另一个源
- prometheus - 如何读取 container_cpu_cfs_throttled_seconds_total 指标?
- excel - 用两个标准对不同的时间值实例求和
- matlab - 为什么从matlab得到的卷积与理论上得到的不同?
- sql - 在 SQL RAW 查询中获取数据,格式与我们在 Laravel 中使用预加载方法获取的格式相同
- save - 在 R_ py_call_impl(callable, dots$args, dots$keywords) 中导入模型:AttributeError: 'NoneType' object has no attribute 'get'
- wordpress - Wordpress REST API 缺少身份验证标头
- javascript - 如何通过从旧字符串中删除与正则表达式不匹配的任何内容来创建新字符串(在 JavaScript 中)
- python - 如何让 WebSocket 服务器/客户端与两方通信