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

♀尐吖头ヾ 提交于 2019-12-11 02:48:41

问题


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

回答1:


I have created the unit test with Nunit (which is almost the same withy XUnit) and I mocked dependencies with Moq. There might be some errors due to online C# compiler but code shown below will give you the idea.

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



回答2:


You can use an instance DefaultModelBindingContext to pass into 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.



来源:https://stackoverflow.com/questions/53909624/how-to-write-unit-test-for-custom-model-binder-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!