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

如果別人知道如何跳過繼承的方法就像我原來問的話,我會接受的。如果不是,那麼最終我會接受這個答案。

相關問題