2013-03-04 114 views
3

我目前正在爲抽象類創建一個單元測試,名爲Component。 VS2008編譯我的程序沒有問題,所以我能夠在解決方案中創建一個單元測試項目。有一件事我注意到,雖然是測試文件被創建時,有這些方法,我以前從未見過:如何正確測試抽象類

internal virtual Component CreateComponent() 
     { 
      // TODO: Instantiate an appropriate concrete class. 
      Component target = null; 
      return target; 
     } 


internal virtual Component_Accessor CreateComponent_Accessor() 
     { 
      // TODO: Instantiate an appropriate concrete class. 
      Component_Accessor target = null; 
      return target; 
     } 

我相信這是創建一個具體Component類。

在每個測試方法,有這樣一行:

Component target = CreateComponent(); // TODO: Initialize to an appropriate value

我怎麼初始化這個適當的值?或者,我如何實例化一個合適的具體類,如上面的CreateComponentCreateComponent_Accessor方法所述?

這裏是抽象類的構造函數,額外的信息:

protected Component(eVtCompId inComponentId, eLayer inLayerId, IF_SystemMessageHandler inMessageHandler)

回答

11

你不能實例化一個抽象類。所以你可以在你的單元測試項目中編寫這個抽象類的模擬實現(你應該在那裏實現抽象成員),然後調用你正在測試的方法。你可以有不同的模擬實現來測試你的類的各種方法。

作爲替代編寫模擬實現,你可以使用mock框架,如犀牛嘲笑,起訂量,NSubstitute,......這能簡化這一任務,並允許您定義類的抽象成員的期望。


UPDATE:

正如在評論部分要求在這裏是一個例子。

讓我們假設你有你想要的單元測試下面的抽象類:

public abstract class FooBar 
{ 
    public abstract string Foo { get; } 

    public string GetTheFoo() 
    { 
     return "Here's the foo " + Foo; 
    } 
} 

現在,在你的單元測試項目,你可以通過編寫一個派生類實現與嘲笑值的抽象成員實現:

public class FooBarMock : FooBar 
{ 
    public override string Foo 
    { 
     get { return "bar" } 
    } 
} 

,然後你可以編寫針對GetTheFoo方法單元測試:

// arrange 
var sut = new FooBarMock(); 

// act 
var actual = sut.GetTheFoo(); 

// assert 
Assert.AreEqual("Here's the foo bar", actual); 

並且使用模擬框架(在我的例子中爲Moq),你不需要在單元測試中實現這個抽象類,但是你可以直接使用模擬框架來定義被測方法依賴的抽象成員的期望值:

// arrange 
var sut = new Mock<FooBar>(); 
sut.Setup(x => x.Foo).Returns("bar"); 

// act 
var actual = sut.Object.GetTheFoo(); 

// assert 
Assert.AreEqual("Here's the foo bar", actual); 
+0

只是爲了澄清,與_mock實現你的意思是這個抽象class_的,創建一個派生類,並實現所有抽象成員... – DHN 2013-03-04 08:25:41

+1

這將是非常有益的,如果你會告訴我這兩個模擬實現的一些例子並使用一個模擬框架(我有Moq框架,一直在使用它的接口) – Anthony 2013-03-04 08:25:51

+0

當然,我已經更新了我的答案,爲您提供一個示例。 – 2013-03-04 08:39:24