【问题标题】:Static method mocked via EasyMock and Powermock getting invoked when calling EasyMock.expect()通过 EasyMock 和 Powermock 模拟的静态方法在调用 EasyMock.expect() 时被调用
【发布时间】:2014-01-04 11:38:58
【问题描述】:

我正在使用 TestNG、EasyMock 和 PowerMock 进行测试。根据下面的代码,我试图模拟从被测静态方法(fetchAuthenticator)调用的静态方法。当我运行测试时,调用 EasyMock.expect 时会执行 executeHttpGet 方法。

@PrepareForTest(Metadata.class)
public class MetadataTest extends PowerMockTestCase {
@Test
public void testPatience(){
PowerMock.mockStatic(HttpHelper.class);
EasyMock.expect(
    HttpHelper.executeHttpGet(EasyMock.anyString()))
    .andReturn(
        "{\"response\":\"some_value\"}");
PowerMock.replay(HttpHelper.class);

String response = Whitebox.invokeMethod(Metadata.class,
    "fetchAuthenticator",
    "something-else",
    "somesite.com", "another-value");
assertNotNull(response);
    }
}

我发现了类似的问题,但没有答案。 EasyMock: Actual function gets called while passing as an argument to EasyMock.expect

【问题讨论】:

  • 这里有什么问题?
  • 其实用Mockito更好。
  • 为什么在不期望的情况下调用了该方法?

标签: java unit-testing static easymock powermock


【解决方案1】:

你忘了包括:

@RunWith(PowerMockRunner.class)

在测试用例的类级别

替换

@PrepareForTest(Metadata.class)

@PrepareForTest({ AuthenticationMetadata.class, HttpHelper.class })

【讨论】:

  • 我使用的是 testNG,而不是 junit。但我通过添加 @PrepareForTest({ AuthenticationMetadata.class, HttpHelper.class }) 来修复它
猜你喜欢
  • 2017-05-19
  • 2016-12-05
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多