如何为在其主体中调用另一个方法的方法编写 xUnit 测试?

How to write xUnit Test for a method which calls another method in its body?

这是 class 包含 EnqueueJobAsync 方法,我想为其编写测试:

public class ConsumerBaseForTesting
{
    protected IJobStore JobStore { get; private set; }

    public ConsumerBaseForTesting(IJobStore jobStore)
    {
        JobStore = jobStore;
    }

    public async Task<IJob> EnqueueJobAsync(IJob job)
        => await JobStore.CreateAsync(job);
}

这是我的测试,失败并且它的实际 return总是NULL !

public class ConsumerBaseTest
{


    private readonly Mock<IJobStore> _moqIJobStore;
    private readonly ConsumerBaseForTesting _consumerBase;

    public ConsumerBaseTest()
    {
        _moqIJobStore = new Mock<IJobStore>();
        _consumerBase = new ConsumerBaseForTesting(_moqIJobStore.Object);
    }


    [Theory]
    [ClassData(typeof(JobClassForTesting))]
    public async Task EnqueueJobAsyncTest(IJob job)
    {
        var jobResult = await _consumerBase.EnqueueJobAsync(job);

        Assert.Equal(job, jobResult);
    }
    
}

模拟需要设置为做两件事以复制预期的行为。

它需要return完成任务中传递的作业。

//...

public ConsumerBaseTest() {
    _moqIJobStore = new Mock<IJobStore>();
    _consumerBase = new ConsumerBaseForTesting(_moqIJobStore.Object);

    //setup the mock to capture and return the job when CreateAsync(IJob job) is invoked
    _moqIJobStore
        .Setup(_ => _.CreateAsync(It.IsAny<IJob>()))
        .Returns((IJob x) => Task.FromResult(x));     }

//...

.Returns((IJob x) => Task.FromResult(x)) 捕获参数并 return 完成 Task<IJob>