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.

7
  • Do you use any other annotations on your test class? Commented Dec 29, 2017 at 2:43
  • Yes, I use @SuppressWarnings, @RunWith, @ContextConfiguration and @FixMethodOrder. What could go wrong? :) Commented Dec 29, 2017 at 2:45
  • 4
    jUnit may or may not use the same instance of test to run all test methods: stackoverflow.com/questions/19381352/… Also it is better to make tests independent from each other and from execution order. Commented Dec 29, 2017 at 2:47
  • Ah thanks for sharing it. It leads me to an answer :) Commented Dec 29, 2017 at 2:57
  • Well in my case, the execution order is that important. It should be create at first, update and lastly: remove Commented Dec 29, 2017 at 3:08

1 Answer 1

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;

Sign up to request clarification or add additional context in comments.

2 Comments

Great! Can you please mark this as the answer to your question (click the checkbox to make it green)?
Yes, I need to wait for 2 days to accept my own answer bro :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.