2014-08-31 141 views
10

我試圖模擬私人靜態方法anotherMethod()。見下面如何使用PowerMockito模擬私有靜態方法?

public class Util { 
    public static String method(){ 
     return anotherMethod(); 
    } 

    private static String anotherMethod() { 
     throw new RuntimeException(); // logic was replaced with exception. 
    } 
} 

下面的代碼是我測試代碼

@PrepareForTest(Util.class) 
public class UtilTest extends PowerMockTestCase { 

     @Test 
     public void should_prevent_invoking_of_private_method_but_return_result_of_it() throws Exception { 

      PowerMockito.mockStatic(Util.class); 
      PowerMockito.when(Util.class, "anotherMethod").thenReturn("abc"); 

      String retrieved = Util.method(); 

      assertNotNull(retrieved); 
      assertEquals(retrieved, "abc"); 
     }  
} 

但每瓦我運行它,我得到這個例外

java.lang.AssertionError: expected object to not be null 

我想我做錯了與嘲諷東東。任何想法如何解決它?

回答

23

對此,您可以使用PowerMockito.spy(...)PowerMockito.doReturn(...)。 此外,您在您的測試類指定PowerMock亞軍,如下:

@PrepareForTest(Util.class) 
@RunWith(PowerMockRunner.class) 
public class UtilTest { 

    @Test 
    public void testMethod() throws Exception { 
     PowerMockito.spy(Util.class); 
     PowerMockito.doReturn("abc").when(Util.class, "anotherMethod"); 

     String retrieved = Util.method(); 

     Assert.assertNotNull(retrieved); 
     Assert.assertEquals(retrieved, "abc"); 
    } 
} 

希望它可以幫助你。

-1

我不知道你使用的是什麼版本的PowerMock的,但以後的版本中,你應該使用@RunWith(PowerMockRunner.class) @PrepareForTest(Util.class)

話說到此,我發現使用PowerMock是真正有問題的,一個貧窮的一個肯定的標誌設計。如果您有時間/機會來改變設計,我會盡力而爲。

+0

號爲'TestNG'我需要用我的註解。 – Aaron 2014-08-31 16:51:05

4

如果anotherMethod()接受任何參數作爲anotherMethod(參數),該方法的正確調用將是:

PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter);