简体   繁体   English

我们如何(在单元测试时)断言是否在其他语句之前调用了一个语句

[英]How do we (while unit testing) assert if one statement was called before other

we are using RhinoMocks to unit test our wpf app. 我们正在使用RhinoMocks对我们的wpf应用进行单元测试。

in one of the scenarios we have a method -- 在其中一个场景中我们有一个方法 -

public void LetsAdd()
{
    _mockableInterface1.DoSomething();
    _mockableInterface2.DoSomethingElse();
}

Now when I try to unit test LetsAdd method, I can assert if both doSomething() and DoSomethingElse() were called or not. 现在,当我尝试单元测试LetsAdd方法时,我可以断言是否调用了doSomething()和DoSomethingElse()。 but can I somehow also test if they were executed in this very order? 但我能以某种方式测试他们是否按照这个顺序执行?

so in other words can I write a test which fails if I swap the two method calls.. ? 所以换句话说,如果我交换两个方法调用,我可以编写一个失败的测试吗?

Thanks 谢谢

If you have preconditions, the test must fire them prior to the test logic. 如果您有前提条件,则测试必须在测试逻辑之前触发它们。 Never rely on the order of the tests. 永远不要依赖测试的顺序。 If there is particular data that needs to be set up for a test, you should set it up and then clean it after you are finished. 如果需要为测试设置特定数据,则应进行设置,然后在完成后进行清理。 This can be done in any testing library through setup and clean up methods. 这可以通过设置和清理方法在任何测试库中完成。 If your classes are fine grained enough, you can use the class setup and clean up methods, otherwise you have to focus on the test setup and clean up methods. 如果你的类足够精细,你可以使用类设置和清理方法,否则你必须专注于测试设置和清理方法。

You could take the method of testing if things were set up (both methods fired?), but this can end up nullifying your test because one test was run in the "wrong" order. 你可以采用测试方法来设置事情(这两种方法都被触发了吗?),但这最终会导致你的测试无效,因为一个测试是以“错误”的顺序运行的。 But since each test should be autonomous, there is not such thing as "wrong" order. 但由于每个测试都应该是自治的,所以没有“错误”的命令。

In your particular scenario, you should set it up to run in the order you needed tested. 在您的特定方案中,您应该将其设置为按您需要测试的顺序运行。 If all scenarios are valid, you need multiple tests. 如果所有方案都有效,则需要多次测试。 Here is what I mean by all scenarios (DS = DoSomething and DSE = DoSomethingElse): 这就是我所说的所有场景(DS = DoSomething和DSE = DoSomethingElse):

Neither DS or DSE run DS only DSE only Both, DS first Both, DSE first DS或DSE都不运行DS只DSE只有两个,DS首先是两个,DSE优先

If different results are expected, by business rules, then you need all 5 tests. 如果按业务规则预期会有不同的结果,那么您需要进行全部5项测试。 Rather than test for the order of the routines, your goal should be to be explicit about testing, forcing them to run in order. 而不是测试例程的顺序,你的目标应该是明确测试,迫使它们按顺序运行。

If this cannot be accomplished in your tests, then I see two options: 如果在测试中无法完成,那么我会看到两个选项:

  1. Re-architecting the solution to remove the "randomness" 重新构建解决方案以消除“随机性”
  2. Adding some type of tracing for method order that can be queried 为可查询的方法顺序添加某种类型的跟踪

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

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