单元测试不使用派生对象

时间:2014-10-28 08:40:02

标签: c# unit-testing

我正在尝试测试一个实现多个骰子表的函数。我已经得到了一个公式,我正在编写一组测试用例来测试正常操作,然后是两个逻辑案例来防止越界结果。

正在测试的功能是

    public static int getNumberOfStars(Dice ourDice, int mod = 0)
    {
        int roll = ourDice.gurpsRoll() + mod;
        int numStars = (int)(Math.Floor((roll - 1.0) / 5.0));

        //fix a few possible logic bugs.
        if (numStars < 1) numStars = 1;
        else if (numStars > 3) numStars = 3;
        return numStars;           
    }

Dice是一个对象,充当PRNG的接口。有问题的功能滚动3d6。模拟对象是:

    public class FakeDice : Dice
    {
          public int diceRoll;

          public new int gurpsRoll()
         {
             return diceRoll;
         }

      ...
  }

最后,测试用例是

    [TestMethod]
    public void VerifyMaxNumberOfStars()
    {
        FakeDice ourDice = new FakeDice();
        ourDice.diceRoll = 18;
        int numDice = StarReference.getNumberOfStars(ourDice, 3);
        Assert.AreEqual(3, numDice);
    }

结果在运行之间发生变化,导致我相信它不使用新功能,而是使用基本功能。 (此测试从未运行过,但手动运行代码会显示它返回有效结果。)

我做错了什么?

3 个答案:

答案 0 :(得分:1)

你的FakeDice类没有覆盖gurpsRoll()方法,它隐藏了它。

要覆盖实现,您需要在Dice类中将gurpsRoll声明为虚拟,并且您需要在FakeDice类中使用override关键字。

您可以在MSDN上找到有关此行为的更多详细信息http://msdn.microsoft.com/en-us/library/ms173153.aspx

答案 1 :(得分:1)

那是因为new方法不会覆盖它们的基本方法。

new方法只在处理它们声明的类时被调用。如果你使用的是多态,则会调用基本方法

以下是一个例子:

FakeDice fake = new FakeDice();
fake.gurpsRoll();  // calls FakeDice's implementation

Dice dice = fake;
dice.gurpsRoll();  // calls Dice's implementation

您需要将基本方法设为虚拟,然后覆盖它。

请参阅:

答案 2 :(得分:1)

使用new关键字覆盖方法时,只有在将对象装箱为派生对象时才会执行。您需要使您想要覆盖虚拟的方法,如下所示:

public class FakeDice : Dice
{
      public int diceRoll;

      public override int gurpsRoll()
     {
         return diceRoll;
     }

  ...
}

public class Dice 
{
    public virtual int gurpsRoll() {...}
}