【问题标题】:Can I mock a static method in a final class and a non-static method in a different class using PowerMockito?我可以使用 PowerMockito 模拟最终类中的静态方法和不同类中的非静态方法吗?
【发布时间】:2014-01-23 03:28:53
【问题描述】:

我在最终类 A 中有一个静态方法,它调用 B 类中的非静态方法。

我需要模拟 A 中的静态方法和 B 中的非静态方法来添加单元测试。 PowerMock 有针对这种情况的解决方案吗?

【问题讨论】:

  • mock B中的方法需要什么?您可以让静态方法 A 的模拟完成其执行所需的一切。

标签: unit-testing junit powermock


【解决方案1】:

您应该使用 PowerMock 来模拟 A 中的静态方法,使用 Mockito 来模拟 B 中的非静态方法。在 this recent answer 我两者都做:

  • 在 AccountManager 上模拟获取静态方法
  • 在客户经理上模拟 getAccounts 方法

为了更清楚,对于静态模拟:

  1. 将@RunWith(PowerMockRunner.class) 添加到您的测试类
  2. 将@PrepareForTest(A.class) 添加到您的测试类中
  3. 调用 PowerMockito.mockStatic(AccountManager.class);
  4. 使用 when(A.method(any(Param.class))).thenReturn(value); 的存根行为;

对于非静态模拟:

  1. 添加模拟字段@Mock B accountManager;
  2. 在 @Before 注解的方法 MockitoAnnotations.initMocks(this) 中初始化 mock;
  3. Stub 行为 when(B.method()).thenReturn(value);

您可能需要在 A 类上配置 B 对象。在此示例中,我在 get 方法中执行此操作。在你的情况下,它可能会有所不同,你必须弄清楚如何去做。

问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多