简体   繁体   中英

How to save any object which is declared as a class variable and initialized inside a test in JUnit

I am designing test cases in JUnit . My question is how to save any object which is declared as a class variable and initialized inside a test. Currently in such cases I am getting java.lang.NullPointerException .

Below is the brief description- I have three services listed below which needs to be tested-

  1. Service 1(login): It accept a username password pair and returns cookies in response.
  2. Service 2(postmessage): It accept a message, which must be supplied with cookies in the request and returns an unique id of posted message
  3. Service 3(markasread) : It accept a message id, which must be supplied with cookies. The message id, which should be used in Service 3 is returned by service 2.

This is what I was expecting to work-

import static org.junit.Assert.*;
import org.junit.Test;

public class ProfileTest{
    private String cookie;
    private String messageId;

    @Test
    public void loginTest(){
        String username = "demouser";
        String password = "demopassword";

        HttpResponse response = login(username, password);
        cookie = response.getCookie();

        assertEquals(response.getResponse(), "success");
    }

    @Test
    public void postmessageTest(){
        String message = "Hi, this is test message";
        HttpResponse response = postmessage(message, cookie);
        messageId = response.getCookie();

        assertEquals(response.getResponse(), "success");
    }

    @Test
    public void markasreadTest(){
        HttpResponse response = markasread(messageId, cookie);

        assertEquals(response.getResponse(), "success");
    }
}

The answer is you cannot and you should not it. Each run of test cases will have its own copy of class variables. The idea behind this is just that each test case should run independently and should not depend on each other.

It may be possible through some junk code but I really don't have such a recommendation for you.

If possible then try to club the tescases together and run as a single one.

The reason you can't do it is the BlockJUnit4ClassRunner creates a new instance of the test class per leaf method. It constructs the test class with the default constructor.

BlockJUnit4ClassRunner

The relevant code is

protected Object createTest() throws Exception {
    return getTestClass().getOnlyConstructor().newInstance();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM