有没有办法跳过基类测试?

时间:2012-07-17 16:36:24

标签: vs-unit-testing-framework

我正在使用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);
    }
}

1 个答案:

答案 0 :(得分: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);
    }
}

如果其他人知道如何跳过我最初问过的继承方法,那么我会接受。如果没有,那么我最终会接受这个答案。