无法使用RhinoMocks存根

时间:2016-03-05 01:24:42

标签: c# testing nunit

我正在 Visual Studio 2015社区中使用 C# NUnit3 Rhino Mocks 并尝试为我的系统组件编写测试(它不是单元测试)。

尝试使用生成的存根作为TestCaseData提供给TestCaseSource的参数时遇到了问题。我在输出窗口中收到以下错误:

Test adapter sent back a result for an unknown test case. Ignoring result for 'MyTest(Castle.Proxies.IMyInterfaceProxy4c6c716794ef48818f41fd5012345ead)'.
Test adapter sent back a result for an unknown test case. Ignoring result for 'MyTest(Castle.Proxies.IMyInterfaceProxy4c6c716794ef48818f41fd5012345ead)'.

当我重建测试项目时,测试名称出现在VS2015集成测试运行器中,但是一旦我尝试运行它,它就变得灰暗。

这里有一些基于我的测试代码的示例代码:

using NUnit.Framework;
using Rhino.Mocks;
using System.Collections;

namespace FenixLib.Core.Tests
{
    public interface IMyInterface
    {
        int Property { get; }
    }

    [TestFixture]
    class TestMocks
    {
        [Test, TestCaseSource( "TestCases" )]
        public void MyTest(IMyInterface what)
        {
            // Do stuff
        }

        public static IEnumerable TestCases()
        {
            yield return new TestCaseData ( CreateFake ( 2 ) );
            yield return new TestCaseData ( CreateFake ( 4 ) );
        }

        public static IMyInterface CreateFake ( int something )
        {
            var fake = MockRepository.GenerateStub<IMyInterface> ();
            fake.Stub ( x => x.Property ).Return ( something );

            return fake;
        }
    }
}

如果我创建一个包装生成的存根的装饰器类,我已经能够克服这个问题:

public class Decorator : IMyInterface
{
    IMyInterface decorated;

    public Decorator ( IMyInterface decorated )
    {
        this.decorated = decorated;
    }

    public int Property
    {
        get
        {
            return decorated.Property;
        }
    }
}

并按return fake;更改之前的return new Decorator ( fake );。一切都很好。

然而,这在我的真实场景中有点痛苦,因为我的界面不仅具有单个属性,如此示例中更复杂(是的,我知道VS2015可以生成通过装饰字段实现的代码,但那不是重点)。此外,如果我要最终创建一个我希望不能完全实现我的测试目的的接口实现,使用RinhoMocks感觉毫无意义。

无论如何,让我烦恼的是,我不明白为什么它不起作用,因此我问:

任何人都可以帮助我理解为什么没有装饰器的代码不起作用?

1 个答案:

答案 0 :(得分:0)

在发现时,TestExplorer会创建一个进程并要求我们的适配器查找测试。您的TestCaseSource方法运行并生成案例。它有一个由Moq生成的名称。

在程序的生命周期中很久以后,您的测试由Visual Studio执行,它会创建一个不同的进程并要求适配器运行测试。由于我们在一个新进程中运行,因此适配器必须全面发现(即生成)这些情况。最有可能的是,Moq使用不同的名称生成它们。最初创建的案例永远不会运行,NUnit会运行这些新案例,从TestExplorer的角度来看,这些案例从未被发现过。

之前我没有看到过这种症状,但我们遇到类似的问题,即在执行时重新生成随机参数。它本质上是架构的一个问题,只有在适配器可以以某种方式保持最初加载的测试程序集在执行过程中找到时才能解决。

相关问题