簡體   English   中英

如何使用PowerMock與Mockito和TestNG來模擬私有方法

[英]How to mock a private method using PowerMock with Mockito and TestNG

我正在嘗試使用powermock模擬私有方法,但是在MockitoBusinessOperation MockitoBusinessOperation = PowerMock.createPartialMock(MockitoBusinessOperation.class, "inTestMethod");無法識別我的PowerMock MockitoBusinessOperation MockitoBusinessOperation = PowerMock.createPartialMock(MockitoBusinessOperation.class, "inTestMethod"); 我使用了maven,並且在我的pom文件中定義了對嘲笑和powermock的依賴關系

<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);  
}

有人對解決方案有想法或任何線索

根據文檔,您的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>

請嘗試這種方式

  @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);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM