如何在ASP.net Core中编写自定义模型绑定程序的单元测试

时间:2018-12-24 05:47:13

标签: c# unit-testing asp.net-core xunit custom-model-binder

我已经为属性编写了自定义模型活页夹。现在,我正在尝试编写相同的单元测试,但无法为模型绑定器创建对象。谁能帮我 ?下面是我必须为其编写测试的代码。

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

2 个答案:

答案 0 :(得分:4)

我已经使用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 fucntion.
        var unitUnderTest = CreateService();

        //Act
        var result = unitUderTest.BindModelAsync(_mockedContext);

        //Assert
        Assert.IsNotNull(result);
        Assert.IsTrue(result is Task.CompletedTask);
    }
} 

答案 1 :(得分:0)

您可以使用实例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);
    }

这可以替代为bindingContext使用模拟对象。