[英]LINQ `Any` not covered by unit test
我有这个方法:
/// <summary>
/// Moves piece to location, does not verify that this is a valid move
/// </summary>
/// <param name="dest"></param>
public virtual void Move(Coordinate dest)
{
if (Board.IsPieceAtLocation(dest))
{
if (GetAllPossibleKills().Any(p => p.BoardLocation == dest))
{
Board.KillPieceAtLocation(dest);
}
else
{
throw new LocationOccupiedException("Board location already occupied and kill is not valid",this, Board.GetPieceAtLocation(dest));
}
}
BoardLocation = dest;
}
它由两个单元测试覆盖:
[Test]
public void LocationOccupiedTest()
{
Board board = new Board();
board.GenerateNewGamePieces();
Assert.Throws<LocationOccupiedException>(()=>board.GetKing(false).Move(new Coordinate(0,0)));
}
[Test]
public void KillPieceTest()
{
Board board = new Board();
board.GenerateNewGamePieces();
Piece knight = board.GetPieceAtLocation(new Coordinate(1, 0));
knight.Move(new Coordinate(1,4));
Assert.DoesNotThrow(()=>knight.Move(new Coordinate(0,6)));
}
根据覆盖率分析,整个方法都被覆盖了,除了:
if (GetAllPossibleKills().Any(p => p.BoardLocation == dest))
您可以在每行代码旁边看到覆盖状态:
考虑到 if 语句的两个分支都被遍历,我不明白这是怎么回事。
我怎样才能得到这个覆盖?
我怀疑问题是您没有测试Any
的所有可能执行路径。
您可能需要添加额外的测试用例以确保在有其他有效目标时(例如)覆盖非法移动(感谢@Persistence 示例)。
要修复此特定示例,您需要添加一个测试用例,用于在存在其他有效杀伤目标时移动到不是有效杀伤目标的占用空间。
[Test]
public void MoveToOccupiedWithOtherValidTargets()
{
Board board = new Board();
board.GenerateNewGamePieces();
Piece king = board.GetKing(true);
king.Move(new Coordinate(0,5));
board.GetPieceAtLocation(new Coordinate(0,1)).Move(new Coordinate(0,4));
Assert.Throws<LocationOccupiedException>(()=>king.Move(new Coordinate(0,4)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.