Rhino Mocks 异步单元测试

Rhino Mocks async unit testing

环境
Rhino 模拟版本:3.6.1
Visual Studio: 2017
Resharper: 2017.3.3
单位:2.6.4

我 运行 使用 Resharper 一起使用 2 个测试夹具。当我这样做时,出现错误:

System.InvalidOperationException : Previous method 'IService.DoThing();' requires a return value or an exception to throw. at Rhino.Mocks.Impl.RecordMockState.AssertPreviousMethodIsClose() at Rhino.Mocks.Impl.RecordMockState.Replay() at Rhino.Mocks.MockRepository.ReplayCore(Object obj, Boolean checkInsideOrdering) at Rhino.Mocks.RhinoMocksExtensions.Expect[T,R](T mock, Function2 action) at Rhino.Mocks.RhinoMocksExtensions.Stub[T,R](T mock, Function2 action) at MobileServices.Api.Tests.Unit.TestFixture2.d__2.MoveNext() in C:\SCM\MyProject.Tests.Unit\ExampleTests.cs:line 42 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at NUnit.Framework.Internal.AsyncInvocationRegion.AsyncTaskInvocationRegion.WaitForPendingOperationsToComplete(Object invocationResult) at 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();
    }
}

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