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 回答