2013-06-01 55 views
1

我的問題是模擬和測試實例化其他類並調用其方法的方法。對於項目的安全性,我只會不談細節。要測試的方法是A的launch()方法。測試規範希望使b.methodOfB返回null。另一個測試規範將爲c.getinput()方法返回nullPowermock使用其他類中的其他方法返回null來測試靜態方法

public class A{ 

    public static void launch() 
    { 
     //instantiation of other classes that will be used 
     B b = new B(); 
     C c = new C(); 

     //class C has a method that gets user information from the console and returns a string 
     //i would like to mock c.getinput() to return null 
     while (c.getinput().compareToIgnoreCase("q") != 0) { 
      //would also like to mock the b.methodOfB() to return null for testing im having a hard time doing this 
      b.methodOfB();//returns something not null 
     } 

    } 

} 

回答

0

這是使用PowerMockito的單元測試代碼。

@Runwith(PowerMockRunner.class) 
public void class ATest 
{ 

    public void testLaunch() 
    { 
    B b = PowerMockito.mock(B.class); 
    C c = PowerMockito.mock(C.class); 
    PowerMockito.when(c.getInput()).thenReturn(null); 
    PowerMockito.when(b.methodOfB()).thenReturn(null); 
    // now call your methods 
    } 

} 

如果有嘲笑靜態方法中的一類,則必須使用mockStatic(Classname.class),然後嘲笑方法如上。

注:我沒有編譯過這段代碼。我只是在回覆中輸入。如果你喜歡投票:) :)

相關問題