为什么在单独运行时,HostType(“Moles”)的单元测试中的断言会通过,但在使用一组测试运行时会失败?

时间:2010-10-13 16:02:43

标签: c# unit-testing pex pex-and-moles

我最近登上了Pex& amp; 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的“在解决方案中运行所有测试”功能),则第一个断言失败。

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

1 个答案:

答案 0 :(得分:1)

它是否仅仅是使用多个线程执行测试的'运行所有测试'的副作用?那么,Dispose()在Assert触发时还没有运行?

尝试使用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);
}
相关问题