[英]How to test a virtual method defined in an abstract class?
我需要對抽象類中定義的虛擬方法進行單元測試。 但是基類是抽象的,因此我無法創建它的實例。 你推薦我做什么?
這是對以下問題的回應: 我正在考慮是否可以通過抽象類的子類的實例進行測試。 這是個好方法嗎? 我該怎么做?
我不確定您的抽象類是什么樣子,但是如果您有類似的東西:
public abstract class SomeClass
{
public abstract bool SomeMethod();
public abstract int SomeOtherMethod();
public virtual int MethodYouWantToTest()
{
// Method body
}
}
然后,正如@David在評論中建議的那樣:
public class Test : SomeClass
{
// You don't care about this method - this is just there to make it compile
public override bool SomeMethod()
{
throw new NotImplementedException();
}
// You don't care about this method either
public override int SomeOtherMethod()
{
throw new NotImplementedException();
}
// Do nothing to MethodYouWantToTest
}
然后,您只需為單元測試實例化Test
:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
SomeClass test = new Test();
// Insert whatever value you expect here
Assert.AreEqual(10, test.MethodYouWantToTest());
}
}
沒有規則說單元測試不能定義自己的類。 這是相當普遍的做法(至少對我而言)。
考慮標准單元測試的結構:
public void TestMethod()
{
// arrange
// act
// assert
}
該“安排”步驟可以包括設置您要測試的內容的任何合理的操作(沒有測試外部的副作用)。 這可以很容易地包括創建一個類的實例,該類的唯一目的是運行測試。 例如,如下所示:
private class TestSubClass : YourAbstractBase { }
public void TestMethod()
{
// arrange
var testObj = new TestSubClass();
// act
var result = testObj.YourVirtualMethod();
// assert
Assert.AreEqual(123, result);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.