Why does ErrorCollector demands for assignment at the moment of declaration?

ε祈祈猫儿з 提交于 2019-12-08 04:58:48

问题


Checkinging many XML strings, I use the ErrorCollector construction frequently. But still I do not understand how it works.

When I am declaring an ErrorCollector, I have to assign it at once:

@Rule
public ErrorCollector collector= new ErrorCollector();

If I want to refresh the collector before every test, I am putting an assignment

collector= new ErrorCollector();

in the @Before method. But thus the first assignment at the declaration is excessive. But I can't remove it.

What is the sense of this must-to-be-assignment? And how it works? I thought, that @Rule is about the declaration only?

@Matthew Farwell at What is the logic of @Rule(JUnit) declaration and assignment in a Groovy class says "In Java, the JUnit runner checks that the @Rule annotation is applied to a public non-static field or public non-static method which returns either a TestRule or MethodRule." But what is checked here is not the declaration, but the assignment and it is something that happens afterwards, after both building and test construction ?


回答1:


As with most / all @Rules in JUnit, they are refreshed or cleared before each test automatically. So you just declare it as a @Rule as you have listed above. You DO NOT need to do anything to it in your @Before method. We way to think of it is that JUnit will invoke the ErrorCollector before and after each test. Before each test the ErrorCollector can initialize itself (clearing any previously stored errors). After each test, if an error has been collected it reports the error(s).

Here is the source for ErrorCollector

From Comment:

It must be assigned because JUnit must have an instance of the rule to work with. Otherwise the object would be null. Remember that the JUnit code is using reflection to get the instance of the Object with the @Rule annotation and using instanceof to determine if it is a TestRule or MethodRule. I believe the @Before method is called within the Statement and therefore after the Rule is invoked

FROM MatthewFarwell:

When you run a JUnit test, for example, FooTest, then the runner will create an instance of FooTest for each test method. So if you're using public ErrorCollector collector= new ErrorCollector(); as above, then this gets naturally re-instantiated once per test method.

Conclusing: Make sure that you don't save state between your tests! Of course you shouldn't have done that anyway since order is not guaranteed.

Thanks Matt!



来源:https://stackoverflow.com/questions/15966146/why-does-errorcollector-demands-for-assignment-at-the-moment-of-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!