简体   繁体   English

延迟NUnit断言消息评估

[英]Delayed NUnit Assert message evaluation

I have this assert in my test code 我的测试代码中有这个断言

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

that asserts some condition after a period of time and on failure produces a message. 在一段时间后断言某些条件并在失败时产生一条消息。 it fails to run because the message string is constructed when the assert starts and not when the assert ends. 它无法运行,因为消息字符串是在断言开始时构造的,而不是在断言结束时构造的。 therefore the eventData collection is still empty (as it is initially) and the attempt to get the Description of the last item in the collection fails. 因此eventData集合仍然是空的(最初是这样),并且尝试获取集合中最后一项的Description失败。 is there a workaround or decent alternative to this in NUnit or do I have to revert to using Thread.Sleep in my tests? NUnit是否有解决方法或替代方案,或者我必须在我的测试中恢复使用Thread.Sleep

PS: I'm using NUnit 2.5.10. PS:我正在使用NUnit 2.5.10。

You may use this scheme: 您可以使用此方案:

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());

This method is similar to the use Thread.Sleep 此方法类似于使用Thread.Sleep

In NUnit version 3.50 I had to use a different syntax. 在NUnit版本3.50中,我不得不使用不同的语法。 Here is the example: 这是一个例子:

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


This will test whether yourCondition is true waiting a certain maximum time using the DelayedConstraint created by the Is.True.After method. 这将测试是否yourCondition为真等待使用某一最大时间DelayedConstraint通过创建Is.True.After方法。

In this example the DelayedConstraint is configured to use maximum time of 100 seconds polling every 0.1 seconds. 在此示例中, DelayedConstraint配置为每0.1秒使用100秒轮询的最大时间。

See aslo the legacy NUnit 2.5 documentation for DelayedConstraint . 见ASLO对于传统NUnit的2.5文档DelayedConstraint

The simplest answer is "don't include that text in your failure message". 最简单的答案是“不要在失败消息中包含该文本”。 I personally almost never include a failure message; 我个人几乎从不包含失败信息; if your test is atomic enough you don't need to do it. 如果你的测试足够原子,你就不需要这样做了。 Usually if I need to figure out a cryptic failure, only a debugger helps anyway. 通常,如果我需要弄清楚一个神秘的失败,那么只有调试器才有帮助。

If you really want to do it, this code should work without managing the threads yourself. 如果你真的想这样做,这段代码应该可以自己管理线程。

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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM