简体   繁体   中英

setUp() not being called in JUnit

For some reason, the setUp() method of my test class is not being called before my test method.

import static org.junit.jupiter.api.Assertions.*;
import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.Test;

class BlockchainAuctionTest {
    private BlockchainAuction auction;

@Before
public void setUp() {
    auction = new BlockchainAuction();
    System.out.println("setUp");
}

@After
public void tearDown() {
    System.out.println("tearDown");
}

@Test
void testOneBid() {
    Bid bid = new Bid("Bitcoin", "Devon", 1.0);
    assertTrue(auction.recordNewBid(bid), "first bid should be added without error");
}
}

Specifically, I am getting a null pointer exception on the line that says

assertTrue(auction.recordNewBid(bid), "first bid should be added without error");

because auction has not been initialized. I am using Eclipse.

You're using a JUnit 5 @Test but JUnit 4 @Before / @After .

You need to use @BeforeEach / @AfterEach from org.junit.jupiter .

From what it looks like, you can try changing the import from

import org.junit.jupiter.api.Test;

to

import org.junit.Test;

Well, For me this is how it worked. I have used:

import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach;


And it worked. I have also used

import org.junit.Before; import org.junit.Test;


It also worked. Any other combination doesn't worked for me.

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