2012-07-17 81 views
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); 
    } 
} 

回答

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); 
    } 
} 

如果别人知道如何跳过继承的方法就像我原来问的话,我会接受的。如果不是,那么最终我会接受这个答案。

相关问题