0

我正在创建一个用于对应用程序进行单元测试的 TestClass,我想做的一件事是运行一个测试方法,检查方法是否正确运行,根据结果在测试类中的类属性中存储一个值,然后使用它值在后面的方法中。

我试过这样做,发现一旦编译器从一种方法移动到另一种方法,我设置的所有属性都会被清除干净。我检查了断点,在第一个方法的末尾,值在属性中,然后在第二个方法的开头,相同的属性为空。

查了一下,似乎没有其他人在尝试同样的事情,所以是否可以在方法之间共享一个值,还是我采取了错误的方法?

提前致谢。

4

3 回答 3

5

You are taking the wrong approach.

Unit tests, by definition, should be completely self-contained and deterministic. They should not depend on one another.

You should be able to refactor out the repetitive portion of your first unit test into a helper method which can be invoked by your other unit test. The work will be done twice, but Unit Tests should be really fast, so the overhead should be really minimal.

于 2012-07-31T16:45:42.803 回答
2

It's not the compiler - it's the test runner which will (potentially) create a new instance for each test.

Tests should generally be independent - even if you could find a way of getting this to work, I would avoid doing so. Design your way around it as best you can.

于 2012-07-31T16:44:30.900 回答
1

无论您使用什么测试框架,这对我来说都是不好的做法。所有自动化测试(更不用说正式的单元测试)都应该相互独立。静态字段/属性可能会起作用,但我建议先重构您的测试。

于 2012-07-31T16:46:29.507 回答