gpt4 book ai didi

c# - 单元测试未涵盖 LINQ `Any`

转载 作者:行者123 更新时间:2023-12-04 09:23:55 26 4
gpt4 key购买 nike

我有这个方法:

/// <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))您可以在每行代码旁边看到覆盖状态:
Coverage Screenshot
我不明白在遍历 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)));
}

关于c# - 单元测试未涵盖 LINQ `Any`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63054967/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com