How do I share state between JUnit tests?
java, junit
Solution
You will need a static variable for this because each test gets its own instance of the test class.
Use this pattern:
private static String uuid;
private void login() {
// Run this only once
if (null != uuid) return;
... talk to your server ...
uuid = responseFromServer.getUuid();
}
@Test
public void testLogin() {
login();
assertNotNull( uuid );
}
@Test
public void someOtherTest() {
login();
... test something else which needs uuid ...
}
@Test
public void testWithoutLogin() {
... usual test code ...
}
This approach makes sure that `login()` is called for each test that needs it, that it's tested on its own and that you can run each test independently.
Problem
I have a test class extending `junit.framework.TestCase` with several test methods.Each method opens a HTTP connection to server and exchange request and response json strings.One method gets a response with a string called UID(similar to sessionId) which i need to use in subsequent requests to the server. I was previously writing that string to a file and my next requests read that file for string.I am running one method at a time.Now I am trying to use that string without file operations.I maintained a hastable(because there are many UIDs to keep track of) in my test class as instance variable for the purpose , but eventually found that class is getting loaded for my each method invocation as my static block is executing everytime.This is causing the loss of those UIDs. How do I achieve this without writing to file and reading from it? I doubt whether my heading matches my requirement.Someone please edit it accordingly.