I found something strange in my project. I create a test class using JUnit to test my service layer. The service layer itself is not my question. My problem is, I don't know why after I assigned a value to an int variable in my first test method, and then when I try to use that value in the second test method, the variable value is 0
Executed in order because I use @FixMethodOrder(MethodSorters.NAME_ASCENDING)
int id;
@Test
public void firstMethodToTest() {
id = 10;
System.out.println(id); // here printed correctly 10
}
@Test
public void secondMethodToTest() {
System.out.println(id); // here printed 0
}
I also try to change int
to Integer
but it returns null
not 0
anymore. I wonder if in JUnit Test class like this, Java variable acts differently. Thanks.
Thanks to @Ivan for giving me a clue to the answer
For each test method (the method annotated with @Test
), a new instance of YourTestClass will be created. This is the behavior of Junit.
So, the point is if you want to use a class member for all test methods, just declare the variable as static. In my case: static int id;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.