0

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.

Hobas Matius
  • 199
  • 1
  • 2
  • 14
  • Do you use any other annotations on your test class? – Ivan Dec 29 '17 at 02:43
  • Yes, I use `@SuppressWarnings`, `@RunWith`, `@ContextConfiguration` and `@FixMethodOrder`. What could go wrong? :) – Hobas Matius Dec 29 '17 at 02:45
  • 4
    jUnit may or may not use the same instance of test to run all test methods: https://stackoverflow.com/questions/19381352/does-junit-reinitialize-the-class-with-each-test-method-invocation Also it is better to make tests independent from each other and from execution order. – Ivan Dec 29 '17 at 02:47
  • Ah thanks for sharing it. It leads me to an answer :) – Hobas Matius Dec 29 '17 at 02:57
  • Well in my case, the execution order is *that* important. It should be create at first, update and lastly: remove – Hobas Matius Dec 29 '17 at 03:08
  • It's really not a great idea to depend on the order of test methods. It's not guaranteed, unless you use MethodSorters in JUnit 4. It sounds like you want three different tests, with setup steps to populate the data than you need to update/delete. – Riaan Nel Dec 29 '17 at 09:16
  • Yes I use `@FixMethodOrder(MethodSorters.NAME_ASCENDING)` – Hobas Matius Dec 29 '17 at 11:28

1 Answers1

2

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;

Hobas Matius
  • 199
  • 1
  • 2
  • 14