【问题标题】:How to mock a private method using PowerMock with Mockito and TestNG如何使用 PowerMock 和 Mockito 和 TestNG 模拟私有方法
【发布时间】:2013-01-18 01:20:10
【问题描述】:

我正在尝试使用 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);  
}

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

【问题讨论】:

  • 您应该真正考虑在编辑器中使用空格而不是制表符,这就是格式不能很好地复制的原因。空格 (1) 中的空间量是通用的,制表符不是。
  • 感谢格式修复

标签: java maven testng mockito powermock


【解决方案1】:

根据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>

【讨论】:

    【解决方案2】:

    请试试这个方法

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 2013-07-17
      • 2013-01-06
      • 2014-02-03
      • 1970-01-01
      • 2018-10-19
      • 2023-03-12
      相关资源
      最近更新 更多