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. 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 function.
        var unitUnderTest = CreateService();
        //Act
        var result = unitUnderTest.BindModelAsync(_mockedContext);
        //Assert
        Assert.IsNotNull(result);
        Assert.IsTrue(result is Task.CompletedTask);
    }
} 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With