基於狀態的測試

給定這個簡單的類,我們可以通過斷言在呼叫 ShaveHead 方法後將 HairLength 變數的狀態設定為零來測試 ShaveHead 方法是否正常工作。

public class Person
{
    public string Name;
    public int HairLength;
    
    public Person(string name, int hairLength)
    {
        this.Name = name;
        this.HairLength = hairLength;
    }
    
    public void ShaveHead()
    {
        this.HairLength = 0;
    }
}

[Test]
public void Person_ShaveHead_SetsHairLengthToZero()
{
    Person personUnderTest = new Person("Danny", 10);
    
    personUnderTest.ShaveHead();
    
    int hairLength = personUnderTest.HairLength;
    
    Assert.AreEqual(0, hairLength);
}