I’m trying to cleanup my tests by always resetting to a known state before each test. In JUnit it seems that the best way to do this is to have a setup() method that sets the values for some fields. When running tests in parallel the field is always correct since each test is executed in a new instance of the test.
However in TestNG this doesn’t seem to be the case. According to a post on their mailing list, setting fields in @BeforeMethod in a multithreaded testing doesn’t guarantee their value.
As I need the classes I’m testing to be in a known state, is there a cleaner solution to this than using DataProvider or saying “Don’t ever run tests in mulithreaded mode”?
There is only one difference between TestNG and JUnit in this specific area: JUnit will create a brand new instance of your test before each test method, TestNG will not.
What this means is that with TestNG, values stored in fields by test methods will be preserved between invocations, which is very useful if this object is complex and takes time to create. It also helps speed up test runs since you don’t have to recreate this state from scratch every time.
If you want this state to be reset every time, simply put the initialization code in @BeforeMethod, like you do with JUnit (except it’s called @Before).
As for multithreading, I don’t understand why you are saying that there is no guarantee about that value, can you be more specific?