Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I share state between JUnit tests?

Tags:

java

junit

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.

like image 522
Vinay thallam Avatar asked Jul 10 '12 09:07

Vinay thallam


2 Answers

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.

like image 121
Aaron Digulla Avatar answered Nov 02 '22 14:11

Aaron Digulla


JUnit will create a new instance of the class for each test. Consequently you should likely set up and store this info as static to the class, using a @BeforeClass annotated static method.

See this SO answer for more info.

like image 30
Brian Agnew Avatar answered Nov 02 '22 14:11

Brian Agnew