我似乎无法弄清楚为什么我的一个测试失败了.
这是测试:
@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));
}
Run Code Online (Sandbox Code Playgroud)
我设置了一个断点,并多次完成整个过程.它进入了类中的第二个if语句ChessPiece,似乎抛出了异常.然后该过程返回到Rook类并在super块下返回false .
关于发生了什么的任何想法?谢谢
相关代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
当您在评论中写下时,JUnit 会告诉您出了什么问题:
我得到“java.lang.AssertionError:预期异常:java.lang.IllegalArgumentException
你得到一个 AssertionError,可能来自在预期异常被抛出之前的断言,或者因为异常被处理然后执行的断言失败。
如果您从注释中删除“预期”值,JUnit 将为您提供断言失败的确切位置(又名堆栈跟踪)
它进入ChessPiece类的第二个if语句,并且似乎抛出异常。然后,该过程返回Rook类,并在超级块下返回false。
正在发生的事情是在第一线isValidMove()的Rook类调用super,以便控制去那里的方法,但由于第二个条件if没有得到满足,它抛出IllegalArgumentException,然后控制返回到子类,即Rook它不能return false现在作为超级已经抛出异常等等异常将从此方法中抛出,并从junit complainsIfFromLocIsDifferentObject方法中抛出。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这个测试案例对我来说是正确的。
| 归档时间: |
|
| 查看次数: |
41808 次 |
| 最近记录: |