1

C# 4.0、Visual Studio 2010 を使用しており、メソッド/クラスにMicrosoft.VisualStudio.TestTools.UnitTesting名前空間の属性で注釈を付けています。

テストクラスで継承を使用したいと思います。追加の継承はそれぞれ、変更または作成されているものを表します。基本クラスからテストを実行しないようにできれば、すべて問題ありません。大まかな例を次に示します。

public class Person
{
    public int Energy { get; private set; }

    public int AppleCount { get; private set; }

    public Person()
    {
        this.Energy = 10;
        this.AppleCount = 5;
    }

    public void EatApple()
    {
        this.Energy += 5;
        this.AppleCount--;
    }
}

[TestClass]
public class PersonTest
{
    protected Person _person;

    [TestInitialize]
    public virtual void Initialize()
    {
        this._person = new Person();
    }

    [TestMethod]
    public void PersonTestEnergy()
    {
        Assert.AreEqual(10, this._person.Energy);
    }

    [TestMethod]
    public void PersonTestAppleCount()
    {
        Assert.AreEqual(5, this._person.AppleCount);
    }
}

[TestClass]
public class PersonEatAppleTest : PersonTest
{
    [TestInitialize]
    public override void Initialize()
    {
        base.Initialize();

        this._person.EatApple();
    }

    [TestMethod]
    public void PersonEatAppleTestEnergy()
    {
        Assert.AreEqual(15, this._person.Energy);
    }

    [TestMethod]
    public void PersonEatAppleTestAppleCount()
    {
        Assert.AreEqual(4, this._person.AppleCount);
    }
}
4

1 に答える 1

0

同僚に尋ねたところ、初期化コードをテストから分離することを提案されました。すべてのセットアップ コードを継承しますが、特定のセットアップのすべてのテストを、そのセットアップ コードを継承するクラスに配置します。したがって、上記は次のようになります。

public class Person
{
    public int Energy { get; private set; }

    public int AppleCount { get; private set; }

    public Person()
    {
        this.Energy = 10;
        this.AppleCount = 5;
    }

    public void EatApple()
    {
        this.Energy += 5;
        this.AppleCount--;
    }
}

[TestClass]
public class PersonSetup
{
    protected Person _person;

    [TestInitialize]
    public virtual void Initialize()
    {
        this._person = new Person();
    }
}

[TestClass]
public class PersonTest : PersonSetup
{
    [TestMethod]
    public void PersonTestEnergy()
    {
        Assert.AreEqual(10, this._person.Energy);
    }

    [TestMethod]
    public void PersonTestAppleCount()
    {
        Assert.AreEqual(5, this._person.AppleCount);
    }
}

[TestClass]
public class PersonEatAppleSetup : PersonSetup
{
    [TestInitialize]
    public override void Initialize()
    {
        base.Initialize();

        this._person.EatApple();
    }
}

[TestClass]
public class PersonEatAppleTest : PersonEatAppleSetup
{
    [TestMethod]
    public void PersonEatAppleTestEnergy()
    {
        Assert.AreEqual(15, this._person.Energy);
    }

    [TestMethod]
    public void PersonEatAppleTestAppleCount()
    {
        Assert.AreEqual(4, this._person.AppleCount);
    }
}

私が最初に尋ねたように、他の誰かが継承されたメソッドをスキップする方法を知っていれば、それを受け入れます。そうでない場合は、最終的にこの回答を受け入れます。

于 2012-07-17T17:15:52.637 に答える