如果WaterContainer,则自动重新填充的Nunitest

本文关键字:填充 Nunitest 新填充 WaterContainer 如果 | 更新日期: 2023-09-27 17:59:44

我想测试水容器是否在空的时候重新装满,下面是我的方法代码:

//Tests if the water is refilled if empty.
public void RefillWaterContainerTest()
{
    Console.Write("Test the water refill");
    int EContainer = new WaterContainer();
    FillUpContainer();
    Assert.AreEqual(0, EContainer); 
}

其余代码如下:

public class WaterContainer : Container {
    public WaterContainer(int level) { Level = level; }
    public override void GetContent() { 
    if (HasContent()) {
            Level -= 1;
        } else {
            if (FillUpWater() == false) {
                throw new EmptyContainerException("No water.");
            } else {
                Level -= 1;
            }
        }
    }
    protected bool FillUpWater() {
        WaterTap tap = new WaterTap();
        if (tap.FillUpContainer()) {
            Level = 5; return true;
        } else {
            return false;
        }
    }
} //And the water tap class: class WaterTap { public bool FillUpContainer() { return true; } }

如果WaterContainer,则自动重新填充的Nunitest

如果WaterTap.FillUpContainer总是返回true,那么FillUpWater永远不会返回false,这意味着你永远不会抛出EmptyContainerException,这使得任何测试都毫无意义。我建议先解决这个问题。

之后,您可以使用Assert.Throws.检查异常是否被抛出

Assert.Throws(EmptyContainerException,FillUpContainer);