简体   繁体   English

单元测试未涵盖 LINQ `Any`

[英]LINQ `Any` not covered by unit test

I've got this method:我有这个方法:

/// <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;
}

And it's covered by two unit tests:它由两个单元测试覆盖:

[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)));
}

According to the coverage analysis, the whole method is covered except for:根据覆盖率分析,整个方法都被覆盖了,除了:

if (GetAllPossibleKills().Any(p => p.BoardLocation == dest))

You can see the coverage status next to each line of code:您可以在每行代码旁边看到覆盖状态:

覆盖范围截图

I don't understand how that can be the case given both branches of the if statement are traversed.考虑到 if 语句的两个分支都被遍历,我不明白这是怎么回事。

How can I get this covered?我怎样才能得到这个覆盖?

I suspect the issue is that you are not testing all possible execution paths for the Any .我怀疑问题是您没有测试Any的所有可能执行路径。

You may need to add extra test cases to ensure you cover (for example) moving illegally when there are other valid targets (thanks for the example @Persistence).您可能需要添加额外的测试用例以确保在有其他有效目标时(例如)覆盖非法移动(感谢@Persistence 示例)。


To fix this specific example, you'd need to add a test case for moving to an occupied space that isn't a valid kill target when there are other valid kill targets.要修复此特定示例,您需要添加一个测试用例,用于在存在其他有效杀伤目标时移动到不是有效杀伤目标的占用空间。

[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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM