Writing a single unit test consisting of several test cases violates the principles of unit testing?

Should i do

Test1(){
  Assert(TestCase1);
  Assert(TestCase1);
  Assert(TestCase3);
  ...
}

or

Test1(){
  Assert(TestCase1);
}
Test2(){
  Assert(TestCase2);
}
Test3(){
  Assert(TestCase3);
}
...

Note. All test cases are closely related. There are only logical differences between them.

+3
source share
3 answers

One test case = one condition for verification, some people translate the condition into a statement, which is wrong, the condition may consist of one or more statements

Example. Imagine that you are developing a chess game and you have just implemented the movement functionality and want to test it, check the following test example.

public void testPawnCanMoveTwoSquaresAheadFromInitialRow (){
    [...]
    //Test moving first a white pawn
    assertPawnCanMoveTwoSquaersAheadFromInitialRow ("a2", "a4");
    //Test moving fater a black pawn
    assertPawnCanMoveTwoSquaersAheadFromInitialRow ("h7", "h5");
}

private void assertPawnCanMoveTwoSquaersAheadFromInitialRow (String from, String to){
    [...]
    Piece movingPiece = board.getSquareContent(from);
    assertTrue (movingPiece.isPawn ());
    assertTrue (board.move (from, to));
    assertTrue (board.getSquareContent(from).isEmpty());
    assertTrue (board.getSquareContent(to).isPawn());
    [...]
}

, , , , , , , , , .

, :

+8

. Test1 , , ... . , .

0

, , .

You may be tempted to think that the first scenario has the advantage that you can use the same scheme for all statements. But, if your first statement fails, you don’t have enough if the other two will pass.

I would suggest the second, as soon as most test frameworks allow you to make a one-time agreement for many tests.

0
source

Source: https://habr.com/ru/post/1714557/


All Articles