c# - 如何在 ASP.net 核心中为自定义模型绑定器编写单元测试
问题描述
我已经为一个属性编写了自定义模型绑定器。现在我正在尝试为相同的单元测试编写单元测试,但无法为模型绑定器创建对象。谁能帮我 ?下面是我必须编写测试的代码。
public class JourneyTypesModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
bool IsSingleWay = Convert.ToBoolean((bindingContext.ValueProvider.GetValue("IsSingleWay")).FirstValue);
bool IsMultiWay = Convert.ToBoolean((bindingContext.ValueProvider.GetValue("IsMultiWay")).FirstValue);
JourneyTypes journeyType = JourneyTypes.None;
bool hasJourneyType = Enum.TryParse((bindingContext.ValueProvider.GetValue("JourneyType")).FirstValue, out journeyType);
if (!hasJourneyType)
{
if (IsSingleWay)
journeyType = JourneyTypes.Single;
else journeyType = JourneyTypes.MultiWay;
}
bindingContext.Result = ModelBindingResult.Success(journeyType);
return Task.CompletedTask;
} }
解决方案
我使用 Nunit 创建了单元测试(这与 XUnit 几乎相同),并使用 Moq 模拟了依赖项。由于在线 C# 编译器可能会出现一些错误,但下面显示的代码将为您提供思路。
[TestFixture]
public class BindModelAsyncTest()
{
private JourneyTypesModelBinder _modelBinder;
private Mock<ModelBindingContext> _mockedContext;
// Setting up things
public BindModelAsyncTest()
{
_modelBinder = new JourneyTypesModelBinder();
_mockedContext = new Mock<ModelBindingContext>();
_mockedContext.Setup(c => c.ValueProvider)
.Returns(new ValueProvider()
{
// Initialize values that are used in this function
// "IsSingleWay" and the other values
});
}
private JourneyTypesModelBinder CreateService => new JourneyTypesModelBinder();
[Test]
public Task BindModelAsync_Unittest()
{
//Arrange
//We set variables in setup function.
var unitUnderTest = CreateService();
//Act
var result = unitUnderTest.BindModelAsync(_mockedContext);
//Assert
Assert.IsNotNull(result);
Assert.IsTrue(result is Task.CompletedTask);
}
}
推荐阅读
- node.js - 使用 api 更改 Twitter 用户名
- r - 使用 lightgbm Tweedie 目标将 SHAP 值从原始单位转换为原生单位?
- microsoft-graph-api - Microsoft Graph API 调用 getOffice365ActiveUserDetail 失败并出现 HTTP 403
- java - 如何使用条件 Scanner hasNext() 退出 while 循环
- javascript - 如何在 reactjs 的子组件中制作过滤器?
- python - 如何更新 Flask 页面之间的变量?
- python - 多个 netcdf 与 xarray 或 satpy 的空间合并/组合
- python - Messenger 中的聊天机器人 Python - 请求
- sql - sql中的二维比较
- python - 在 Python 中使用 ElementTree 创建多级层次结构 XML 树