@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.