I am using JUnit for the first time and I have small problem: the setUp() method doesn't seem to work for me.

public class ClientTest {
    private Client a;


    @BeforeClass
    public static void setUpBeforeClass() throws Exception {

    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Before
    public void setUp() throws Exception {
        Client a = new Client();
    }

    @After
    public void tearDown() throws Exception {
        Client a = null;        
    }

    @Test
    public void testSetBonusPoints() {
        a.setBonusPoints(30);
        assertTrue(30 == a.getBonusPoints());

    }

}

If I initialize the Client a in setUp(), then I receive a NullPointerException. If I initialize it at declaration everything is working fine.

Here is the class Client:

public class Client {
    private int bonusPoints;

    public void setBonusPoints(int bonusPoints) throws IllegalArgumentException {
        this.bonusPoints = bonusPoints;
    }


    public int getBonusPoints() {
        return bonusPoints;
    }

}

Recommended Answers

All 2 Replies

Hmm please can you post the full error message? with line number etc

Java basics!
Class variable Client a will never get initialized because you cretae another temporary variable in setUp method. Just do a = new Client() same goes for tearDown

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.