使用NUnit和Moq测试该调用

时间:2016-09-08 15:41:15

标签: c# unit-testing async-await nunit moq

我有一段生产代码,其中一些长期任务必须完成才能完成其他任务(参见下面的示例)。我能够测试呼叫顺序但 await(示例中缺少)。我该怎么办来测试呢?

using System.Threading.Tasks;
using Moq;
using NUnit.Framework;

namespace TestingCallsAwaitedDemo
{
    public interface IFoo
    {
        Task DoThisFirst();
    }

    public interface IBar
    {
        void ThenDoThis();
    }

    public class Demo
    {
        private readonly IFoo _foo;
        private readonly IBar _bar;

        public Demo(IFoo foo, IBar bar)
        {
            _bar = bar;
            _foo = foo;
        }

        public async Task DoSomething()
        {
            _foo.DoThisFirst(); // The await is missing. How do I force its presence with a test?
            _bar.ThenDoThis();
        }
    }

    [TestFixture]
    public class DemoTests
    {
        private Demo classUnderTest;
        private Mock<IFoo> fooMock;
        private Mock<IBar> barMock;

        [SetUp]
        public void Setup()
        {
            fooMock = new Mock<IFoo>();
            barMock = new Mock<IBar>();
            classUnderTest = new Demo(fooMock.Object, barMock.Object);
        }

        [Test]
        public async Task MustFinishDoThisFirstBeforeCallingThenDoThis()
        {
            var callOrder = string.Empty;
            fooMock.Setup(v => v.DoThisFirst())
                .Callback(() => callOrder += "DoThisFirst >> ");
            barMock.Setup(v => v.ThenDoThis())
                .Callback(() => callOrder += "ThenDoThis >> ");

            await classUnderTest.DoSomething();

            Assert.AreEqual(
                "DoThisFirst >> ThenDoThis >> ",
                callOrder);

            //How do I test the missing await?
        }
    }
}

这是一个解决方案。感谢@dvorn

[Test]
public async Task MustFinishDoThisFirstBeforeCallingThenDoThis()
{
    var tcs = new TaskCompletionSource<bool>();
    fooMock.Setup(v => v.DoThisFirst()).Returns(tcs.Task);

    var task = classUnderTest.DoSomething();

    Assert.IsFalse(task.IsCompleted, "Did not await 'DoThisFirst'");
    fooMock.Verify(f => f.DoThisFirst(), Times.Once);
    barMock.Verify(b => b.ThenDoThis(), Times.Never);

    tcs.SetResult(true);
    await task;

    Assert.IsTrue(task.IsCompleted);
    fooMock.Verify(f => f.DoThisFirst(), Times.Once);
    barMock.Verify(b => b.ThenDoThis(), Times.Once);
}

1 个答案:

答案 0 :(得分:1)

TaskCompletionSource<bool> tcs;

设置fooMock返回tcs.Task

var task = classUnderTest.DoSomething();

断言任务未完成。

tcs.SetResult(真)。

现在等待任务。