0

我最近加入了 Pex 和 Moles 的潮流,以便使用许多静态、非虚拟、密封等元素来测试一些逻辑。最近,我开始看到一些我无法从一些测试中解释的行为.

我存根的接口的一些方法返回 void,因此我将存根设置为更新布尔变量以指示它们已被调用的委托。这就是我正在做的事情:

[TestMethod]
[HostType("Moles")]
    public void UnitTestX()
    {
        bool disposeCalled = false;
        bool getCalled = false;

        ClassX classX = new ClassX();
        var data = new SIClassXData
                       {
                           Dispose = () => disposeCalled = true,
                           Get = () => getCalled = true,
                           ClassXGet = () => classX
                       };

        MDataLayerFactory.CreateDataLayerObject(() => (IClassXData)data);

        Assert.IsTrue(disposeCalled);
        Assert.IsTrue(getCalled);
    }

无论出于何种原因,如果我单独运行此测试,上述断言就会成功。但是,如果我将测试与程序集中的所有其他测试一起运行(使用 Visual Studio 的“在解决方案中运行所有测试”功能),第一个断言将失败。

我想知道为什么会发生这种情况,以及我需要改变什么来解决这个问题。

4

1 回答 1

1

这可能只是使用多个线程执行测试的“运行所有测试”的副作用吗?那么,在 Assert 触发时 Dispose() 还没有运行?

尝试使用 ManualResetEvent 阻止测试方法,直到 Dispose() 运行?就像是;

public void UnitTestX()
{
    // use this to block the test thread until Dispose() is run
    ManualResetEvent mre = new ManualResetEvent(false);

    bool disposeCalled = false;
    bool getCalled = false;

    ClassX classX = new ClassX();
    var data = new SIClassXData
                   {
                       Dispose = () => { 
                          disposeCalled = true; 
                          mre.Set(); // release the test thread now
                       },
                       Get = () => getCalled = true,
                       ClassXGet = () => classX
                   };

    MDataLayerFactory.CreateDataLayerObject(() => (IClassXData)data);

    Assert.IsTrue(mre.WaitOne(1000)); // give it a second to fire
    Assert.IsTrue(disposeCalled);
    Assert.IsTrue(getCalled);
}
于 2012-04-17T22:57:56.203 回答