如何使用PowerMock与Mockito和TestNG模拟私有方法

时间:2013-01-18 01:20:11

标签: java maven testng mockito powermock

我正在尝试使用powermock来模拟私有方法,但我的PowerMock在MockitoBusinessOperation MockitoBusinessOperation = PowerMock.createPartialMock(MockitoBusinessOperation.class, "inTestMethod");中无法识别。我使用了maven,mockito和powermock的依赖项在我的pom文件中定义

<dependency>   
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.8.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-mockito-release-full</artifactId>
    <version>1.4.9</version>
    <scope>test</scope>
</dependency>

我不知道错误是否与使用TestNG的powermock有关,或者我在代码中犯了一些错误。

@PrepareForTest(MockitoBusinessOperation.class)
@Test(enabled = true)
public void testReCalculatePrepaids() throws Exception {
    MockitoBusinessOperation MockitoBusinessOperation = PowerMock.createPartialMock(MockitoBusinessOperation.class, "inTestMethod");
    PowerMock.expectPrivate(MockitoBusinessOperation, "inTestMethod",   Id).andReturn("working fine");

    when(MockitoBusinessService.creditReport(this.Id)).thenReturn(new String("Decline by only Me")); 

    String report = MockitoBusinessService.creditReport(this.Id);
    String mainReport = MockitoBusinessOperation.creditAproved(this.Id);  
}

有人有想法或任何线索导致解决方案

2 个答案:

答案 0 :(得分:0)

根据documentation你的maven文件应该有以下定义:

<properties>
    <powermock.version>1.5</powermock.version>
</properties>
<dependencies>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-testng</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>  
</dependencies>

答案 1 :(得分:0)

请尝试这种方式

  @Test
        public  void  commandEndHandlerTest() throws  Exception
        {
            Method retryClientDetail_privateMethod =yourclass.class.getDeclaredMethod("Your_function_name",null);
            retryClientDetail_privateMethod.setAccessible(true);
            retryClientDetail_privateMethod.invoke(yourclass.class, null);
        }