2014-08-31 65 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); 
相关问题