【发布时间】:2018-04-29 17:11:51
【问题描述】:
我正在尝试为 GetOutOfJail 方法创建单元测试,但我无法找到一种获取它的方法,因为它是私有的,除了测试之外,它不需要公开。我无法更改LandedOnTile 方法的签名,因为它继承了抽象类Tile。
您可能已经猜到了,这是我正在尝试将其作为迷你项目制作的一款大富翁游戏。
public abstract class Tile
{
public abstract int Location { get;}
public abstract void LandedOnTile(Player player);
}
public class JailTile : Tile
{
public override int Location { get; }
Random dice = new Random();
public JailTile()
{
Location = 3;
}
public override void LandedOnTile(Player player)
{
if (player.inJail)
{
GetOutOfJail(player);
}
else
{
Console.WriteLine(player.name + " is just visiting jail");
}
}
private void GetOutOfJail(Player player)
{
int roll = dice.Next(1, 4);
int turnsInJail = player.timeInJail;
if (turnsInJail == 3)
{
player.inJail = false;
Console.WriteLine(player.name + " has spent 3 turns in jail and is now out");
player.timeInJail = 0;
}
else if (turnsInJail < 3 && roll > 2)
{
player.inJail = false;
Console.WriteLine(player.name + " has rolled a 3 and it out of jail");
player.timeInJail = 0;
}
else
{
Console.WriteLine(player.name + " has rolled a lower than a 3 and is in jail for another turn");
player.timeInJail++;
}
}
}
【问题讨论】:
-
为什么要测试私有方法?通过确保调用调用它的公共方法 (
LandedOnTile) 时发生正确的事情来测试它。 -
你到底想测试什么?调用公共方法并断言主题的行为符合预期。没有看到问题出在哪里。
-
在此处阅读相关讨论:stackoverflow.com/questions/9122708/…
-
测试
private方法是错误的,但如果你需要你可以使用反射。 -
瓷砖不应该自己掷骰子。将其抽象为一个代表掷骰子并保存掷骰子的类,然后您可以使用模拟骰子测试此图块。
标签: c# unit-testing