使用 C# 设置起订量

问题描述 投票:0回答:1
public interface Itest 
{
    Public Task ExecuteAsync<TException> (
        Func<Task> action,
        Action<(Exception Exception, int X, int Total)> ontest,
        int? y=null) 
    where TException : Exception;

}

我们需要模拟和设置方法,在设置时面临错误

Func<Task>
Action<(Exception,X,Total)

请建议模拟和设置接口方法 ExecuteAsync

c# unit-testing moq
1个回答
0
投票

快乐的路径检查

[Fact]
public async Task GivenAFlawlessExecuteAsync_WhenICallIt_ThenItIsExecutedOnlyOnce()
{
    //Arrange
    var mocked = new Mock<Itest>();
    mocked.Setup(t => t.ExecuteAsync<Exception>(
        It.IsAny<Func<Task>>(),
        It.IsAny<Action<(Exception, int, int)>>(),
        It.IsAny<int?>()
        ))
        .Returns(Task.CompletedTask);

    var action = () => Task.CompletedTask;
    var ontest = ((Exception, int, int) _) => { };
    var y = 1;

    //Act
    //You should call it through your SUT not directly via .Object
    await mocked.Object.ExecuteAsync<Exception>(
        action,
        ontest,
        y);

    //Assert
    mocked.Verify(t => t.ExecuteAsync<Exception>(
        action,
        ontest,
        y
        ), Times.Once);
}

不愉快的路径检查

[Fact]
public async Task GivenAFaultyExecuteAsync_WhenICallIt_ThenItThrowsTheExpectedException()
{
    //Arrange
    var mocked = new Mock<Itest>();
    mocked.Setup(t => t.ExecuteAsync<Exception>(
        It.IsAny<Func<Task>>(),
        It.IsAny<Action<(Exception, int, int)>>(),
        It.IsAny<int?>()
        ))
        .ThrowsAsync(new NotImplementedException());

    //You should call it through your SUT not directly via .Object
    var theAction = mocked.Object.ExecuteAsync<Exception>(
        () => Task.CompletedTask,
        ((Exception, int, int) _) => { },
        1);

    //Act + Assert
    await Assert.ThrowsAsync<NotImplementedException>(async () => await theAction);
}
© www.soinside.com 2019 - 2024. All rights reserved.