16

我似乎无法弄清楚为什么我的一项测试失败了。

这是测试:

@Test(expected = IllegalArgumentException.class)
public void complainsIfFromLocIsDifferentObject() throws Throwable {
    board.set(make(), 1, 3); //Creates different rook from 'piece'
    assertFalse("ChessPiece Test 2", piece.isValidMove(getValidMove(1, 3), board));
}

我已经设置了一个断点并多次完成了该过程。它进入ChessPiece类中的第二个 if 语句,并且似乎抛出了异常。然后该过程返回类并在块Rook下返回false 。super

关于发生了什么的任何想法?谢谢

相关代码:

public class Rook extends ChessPiece {

    @Override
    public boolean isValidMove(Move m, IChessBoard b) {
        if (super.isValidMove(m, b) == false)
            return false;

        // Add logic specific to rook
        if(m.fromRow == m.toRow || m.fromColumn == m.toColumn)
            return true;
        else 
            return false;
    }
}


public abstract class ChessPiece implements IChessPiece {

    @Override
    public boolean isValidMove(Move m, IChessBoard b) {

        //Verify that there is a piece at the origin
        if (b.pieceAt(m.fromRow,m.fromColumn) == null)
            throw new IllegalArgumentException();

        // Verify that this piece is located at move origin
        IChessPiece piece = b.pieceAt(m.fromRow, m.fromColumn);
        if (this != piece)
            throw new IllegalArgumentException();
     }
}
4

3 回答 3

10

它进入 ChessPiece 类中的第二个 if 语句,似乎抛出了异常。然后该过程返回到 Rook 类并在 super 块下返回 false。

isValidMove()正在发生的事情是Rook类调用方法中的第一行,super所以控制到那里,但是由于不满足第二个条件,if它抛出IllegalArgumentException然后控制返回到子类Rook,即它现在不能return false,因为 super 已经抛出异常所以异常将从该方法外部重新抛出,并将从junitcomplainsIfFromLocIsDifferentObject方法重新抛出。

这将被 JUnit 框架理解并且应该通过测试用例。

@RunWith(value = BlockJUnit4ClassRunner.class)检查测试用例类中是否有此行。

更新:

@RunWith(value = BlockJUnit4ClassRunner.class)
public class Test extends TestCase{

    @Test(expected = IllegalArgumentException.class)
    public void test1() throws Throwable{
        assertFalse(throwException());
    }

    private boolean throwException(){
        throw new IllegalArgumentException();
    }
}

这个测试用例通过了我。

于 2013-03-08T07:07:50.883 回答
7

正如您在评论中所写,JUnit 会告诉您出了什么问题:

我得到“java.lang.AssertionError:预期异常:java.lang.IllegalArgumentException

你得到一个 AssertionError,可能是在预期异常被抛出之前的一个断言,或者是因为异常被处理,然后一个断言执行失败了。

如果您从注释中删除“预期”值,JUnit 将为您提供断言失败的确切位置(又名堆栈跟踪)

于 2013-03-08T08:09:30.300 回答
-1

通常我不会将 JUnit 断言放在我期望异常抛出的代码周围。

所以

@Test(expected = IllegalArgumentException)
public void test() {
   board.set(make(), 1, 3); //Creates different rook from 'piece'
   piece.isValidMove(getValidMove(1, 3), board);
}

否则,异常将在 JUnit 断言语句中引发,该语句将异常包装在 assertionException 中。

于 2013-03-08T08:15:07.993 回答