Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of @Before in Junit Testing

Tags:

java

junit

@Before notation in JUnit Testing is needed because several tests need similar objects created before they can run.

But I don't get the difference between instantiating an object before the testcase function as a global object and putting inside a @Before.

For example, I am testing my chess program and I am testing if my Piece object moves to a correct place by doing :

public class PawnTest { //The Test Class itself

Board board = new Board();

@Test
/**
 * Testing the right movement
 */
public void correctMovementTest() {
    Pawn p1 = new Pawn(Player.UP);
    board.placePiece(4, 3, p1);
    board.movePieceTo(5, 3, p1);
    assertEquals(board.getPiece(5, 3), p1);
}

@Test
/**
 * Testing the right movement
 */
public void correctMovementTest2() {
    Pawn p1 = new Pawn(Player.UP);
    board.placePiece(4, 3, p1);
    board.movePieceTo(6, 3, p1);
    assertEquals(board.getPiece(6, 3), p1);
}

....

So wouldn't it just work if I decalre Board and Pawn p1 outside the testcase method? Why would we need @Before in the test class?

Also, doing this won't work

@Before
public void setup() {
    Board board = new Board();
    Pawn p1 = new Pawn(Player.UP);
}

I thought this would actually set up the objects before the test cases so that I won't have to set them up on every test cases, but the test cases wouldn't actually read the p1 object and the board.

like image 234
user6792790 Avatar asked Mar 09 '23 00:03

user6792790


1 Answers

@Before annotation is used to do something before executing each test case in your class. So, basically you're on the right way. To make your code work, you need to declare your Board and Pawn outside of function scope.

Board board = null;
Pawn p1 = null;

@Before
public void setup() {
    board = new Board();
    p1 = new Pawn(Player.UP);
}

There is also @BeforeClass annotation available to execute some actions once before executing entire test suite - for example start embedded database. Hope it helps!

like image 157
Sergey Prokofiev Avatar answered Mar 15 '23 22:03

Sergey Prokofiev