首页 > 解决方案 > Rhino 模拟异步单元测试

问题描述

环境
Rhino Mocks 版本:3.6.1
Visual Studio:2017
Resharper:2017.3.3
Nunit:2.6.4

我使用 Resharper 一起运行 2 个测试装置。当我这样做时,我得到一个错误:

System.InvalidOperationException:以前的方法'IService.DoThing();' 需要返回值或抛出异常。在 Rhino.Mocks.Impl.RecordMockState.AssertPreviousMethodIsClose() 在 Rhino.Mocks.Impl.RecordMockState.Replay() 在 Rhino.Mocks.MockRepository.ReplayCore(Object obj, Boolean checkInsideOrdering) 在 Rhino.Mocks.RhinoMocksExtensions.Expect[T, R](T 模拟,函数2 action) at Rhino.Mocks.RhinoMocksExtensions.Stub[T,R](T mock, Function2 动作)在 C:\SCM\MyProject.Tests.Unit\ExampleTests.cs:line 42 中的 MobileServices.Api.Tests.Unit.TestFixture2.d__2.MoveNext() --- 堆栈跟踪从上一个异常位置结束抛出---在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 NUnit.Framework.Internal.AsyncInvocationRegion.AsyncTaskInvocationRegion.WaitForPendingOperationsToComplete(Object invocationResult) 在 NUnit.Framework.Internal.Commands.TestMethodCommand.RunAsyncTestMethod(TestExecutionContext context)

当我多次运行这两个测试夹具时,错误的测试源在 TestFixture1.Test1 到 TestFixture2.Test1 之间不断变化。当我单独运行测试装置时,一切都通过了。这是 Rhino Mocks 和线程的问题吗?

using Project.Tests.Unit.SupportingClasses;
using NUnit.Framework;
using System.Threading.Tasks;
using Rhino.Mocks;

namespace Project.Tests.Unit
{
    [TestFixture]
    public class TestFixture1
    {
        private IService _service;

        [SetUp]
        public void SetUp()
        {
            _service = MockRepository.GenerateMock<IService>();
        }

        [Test]
        public async Task Test1()
        {
            _service.Stub(s => s.DoThing()).Return(Task.FromResult(true));

            var response = await _service.DoThing();
        }
    }

    [TestFixture]
    public class TestFixture2
    {
        private IService _service;

        [SetUp]
        public void SetUp()
        {
            _service = MockRepository.GenerateMock<IService>();
        }

        [Test]
        public async Task Test1()
        {
            _service.Stub(s => s.DoThing()).Return(Task.FromResult(true));

            var response = await _service.DoThing();
        }
    }
}

namespace Project.Tests.Unit.SupportingClasses
{
    public interface IService
    {
        Task<bool> DoThing();
    }
}

标签: c#unit-testingasynchronousasync-awaitrhino-mocks

解决方案


是的。您的代码证明这Rhino Mocks 不是线程安全的。我建议您使用Moq,因为它应该可以很好地并行工作。


推荐阅读