2016-08-11 91 views
0
public class A { 
    public void methodOne(int argument) { 
     //some operations 
     B b = methodTwo(int argument); 

     // some operations based on b 
     // switch cases based on returned values of b 

    } 

    private void methodTwo(int argument) 
    DateTime dateTime = new DateTime(); 
    //use dateTime to perform some operations 
} 
+1

不要在評論中提供更多信息。總是更新你的問題。 – GhostCat

回答

0

如果你真的必須嘲笑B類,那麼你可以做如下(不使用PowerMock,而是在JMockit庫):

public class ExampleTest { 
    @Tested A a; 

    @Test 
    public void exampleTest(@Mocked B anyB) { 
     // Record calls to methods on B, if/as needed by code under test: 
     new Expectations() {{ anyB.doSomething(); result = "mock data"; }}; 

     // Exercise the code under test: 
     a.methodOne(123); 

     // Verify a call to some other method on B, if applicable: 
     new Verifications() {{ anyB.someOtherMethod(anyString, anyInt); }}; 
    } 
} 

注意:此測試並不怎麼在意A獲得B。它與實施細節無關,如private methodTwo,因爲一個好的測試應該始終如一。

0

理想情況下,您不需要!

含義:您的methodOne()返回某個值。所以,如果可能的話,你應該更喜歡而不是測試內部。因此,你應該編寫用各種參數調用methodOne()的測試用例;然後聲明該方法返回的值與您的例外相匹配。

如果您確實需要控制該「B」對象才能進行合理的測試,那麼正確的方法是使用依賴注入,並以某種方式向受測試的類提供B對象。因爲那樣你就可以創建一個嘲弄的B並把它交給你的課堂。

換句話說:學習如何編寫可測試的代碼;例如通過觀看這些videos。認真;該材料的每一分鐘都值得你花時間。

+0

謝謝..我會通過視頻 – mani

+0

控制從「A」級使用的對象「B」沒有「*正確的方法」。除此之外,依賴注入是一種選擇,每個選項都有自己的權衡。 –

相關問題