延迟NUnit断言消息评估

我的测试代码中有这个断言

Assert.That(() => eventData.Count == 0, Is.True.After(notificationPollingDelay), "Received unexpected event with last event data" + eventData.Last().Description()); 

在一段时间后断言某些条件并在失败时产生一条消息。 它无法运行,因为消息字符串是在断言开始时构造的,而不是在断言结束时构造的。 因此, eventData集合仍然是空的(最初是这样),并且尝试获取集合中最后一项的Description失败。 在NUnit是否有解决方法或替代方案,或者我必须在我的测试中恢复使用Thread.Sleep

PS:我正在使用NUnit 2.5.10。

您可以使用此方案:

 var constrain = Is.True.After(notificationPollingDelay); var condition = constrain.Matches(() => eventData.Count == 0); Assert.IsTrue(condition, "Received unexpected event with last event data" + eventData.Last().Description()); 

此方法类似于使用Thread.Sleep

在NUnit版本3.50中,我不得不使用不同的语法。 这是一个例子:

 var constraint = Is.True.After( delayInMilliseconds: 100000, pollingInterval: 100); Assert.That( () => yourCondition, constraint ); 

这将使用Is.True.After方法创建的Is.True.After测试yourCondition是否为true,等待某个最大时间。

在此示例中, DelayedConstraint配置为每0.1秒使用100秒轮询的最大时间。

请参阅DelayedConstraint的旧版NUnit 2.5文档。

最简单的答案是“不要在失败消息中包含该文本”。 我个人几乎从不包含失败信息; 如果你的测试足够primefaces,你就不需要这样做了。 通常,如果我需要弄清楚一个神秘的失败,那么只有调试器才能提供帮助。

如果你真的想这样做,这段代码应该可以自己管理线程。

 try { Assert.That(() => eventData.Count == 0, Is.True.After(notificationPollingDelay)); } catch(AssertionException) { throw new Exception("Received unexpected event with last event data" + eventData.Last().Description()); }