2013-02-28 96 views

回答

0

你的意思是模擬內部對象DB不是C的權利?

像你這樣的代碼你不能。您必須將DB注入到A類中。然後在單元測試中注入模擬/存根,而不是與數據庫對話的對象。

編輯: 你可以這樣做(我使用C#):

當然
Class A 
{ 
    private readonly IDb database; 

    // you can inject by hand or using IoC container 
    // if you don't like that you have to pass IDb implementation everywhere 
    // where you create objects of type A you can add another constructor - look under 
    public A(IDb database) 
    { 
     this.database = database; 
    } 

    // here you call the above constructor and pass you original DB object 
    public A() : this(new DB()) 
    { 
    } 

    public boolean do(String s) 
    { 
     C c = database.GetResult(s); 
     .... 
     return yes/no 
    } 
} 

你的DB類必須實現IDB接口。

interface IDb 
{ 
    C GetResults(String s); 
} 

現在,在你測試你這樣做:

var a = new A(new TestDBDoingReturningExactlyWhatYouTellItToReturn()); 

,並在應用程序代碼:

var a = new A(new DB()); 

或無參數的構造函數,不正是線以上

var a = new A(); 
+0

的Mockito不支持類的靜態方法。我如何注入數據庫和方法? – brucenan 2013-03-04 05:59:30

+0

爲了模擬它,DB.GetResult不能是靜態的。你真的需要它是靜態的嗎?沒有太多的理由讓方法變爲靜態的。 – 2013-03-04 10:01:33

+0

我可以將其更改爲非靜態。但是一個數據庫類出現內部方法.DB db = new DB(); C c = db.get();同樣的問題即將到來。我怎樣才能模擬數據庫對象? – brucenan 2013-03-04 11:45:35

相關問題