简体   繁体   English

如何在 ASP.net 核心中为自定义模型绑定器编写单元测试

[英]How to write unit test for custom model binder in ASP.net core

I have written custom model binder for a property.我已经为一个属性编写了自定义模型绑定器。 Now I am trying to write unit test for the same but not able to create object for model binder.现在我正在尝试为其编写单元测试,但无法为模型绑定器创建对象。 Can anyone help me ?谁能帮我 ? Below is the code for which I have to write test.以下是我必须为其编写测试的代码。

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

I have created the unit test with Nunit (which is almost the same withy XUnit) and I mocked dependencies with Moq.我已经使用 Nunit 创建了单元测试(这与 XUnit 几乎相同)并且我使用 Moq 模拟了依赖项。 There might be some errors due to online C# compiler but code shown below will give you the idea.由于在线 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);
    }
} 

You can use an instance DefaultModelBindingContext to pass into BindModelAsync() :您可以使用实例DefaultModelBindingContext传递到BindModelAsync()

    [Fact]
    public void JourneyTypesModelBinderTest()
    {
        var bindingContext = new DefaultModelBindingContext();

        var bindingSource = new BindingSource("", "", false, false);
        var routeValueDictionary = new RouteValueDictionary
        {
            {"IsSingleWay", true},
            {"JourneyType", "Single"}
        };
        bindingContext.ValueProvider = new RouteValueProvider(bindingSource, routeValueDictionary);

        var binder = new JourneyTypesModelBinder();
        binder.BindModelAsync(bindingContext);

        Assert.True(bindingContext.Result.IsModelSet);
        Assert.Equal(JourneyTypes.Single, bindingContext.Result.Model);
    }

This can be an alternative to using a mock object for bindingContext .这可以替代为bindingContext使用模拟对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core中的单元测试标准ViewModel绑定器 - Unit test standard ViewModel binder in ASP.NET Core asp.net Core 2自定义模型Binder,具有复杂的模型 - asp.net Core 2 Custom Model Binder with complex model Asp.Net Core中用于子类的自定义模型活页夹 - Custom Model Binder In Asp.Net Core for Sub Classes 将自定义模型活页夹应用于asp.net核心中的对象属性 - Apply Custom Model Binder to Object Property in asp.net core 自定义模型绑定器 asp.net core 来绑定字典 - Custom Model binder asp.net core to bind dictionary ASP.NET Core 1(RTM)中的自定义DateTime模型绑定器 - Custom DateTime model binder in ASP.NET Core 1 (RTM) 如何在ASP.NET Core中使用支持依赖注入的自定义模型绑定器? - How do I use custom model binder that supports dependency injection in ASP.NET Core? 为 ASP.NET Core 3.1 中的 QueryString 字符串参数自定义 model 绑定器? - Custom model binder for QueryString string parameters in ASP.NET Core 3.1? 如何为 ASP.NET 核心 Web API 应用程序编写程序和启动 cs 文件的单元测试 - How to write unit test for Program and Startup cs file for ASP.NET Core Web API app 用于抽象模型的Asp.Net Core 2.0(MVC)Content Binder - Asp.Net Core 2.0 (MVC) Content Binder for an abstract model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM