且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-02-16 22:30:40

我已经创建了单位使用Nunit进行测试(与XUnit几乎相同),然后使用Moq模拟依赖关系。联机C#编译器可能会导致一些错误,但是下面显示的代码将为您提供这个想法。

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