PowerMock / EasyMock for JMX ManagementFactory

时间:2013-04-16 22:04:12

标签: easymock powermock

我需要模仿以下代码:

final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(testMBean, new ObjectName("testObjectName");

我使用PowerMock来模拟ManagementFactory,其中包含以下代码片段:

  1. 在班级,我配置了:

    @RunWith(PowerMockRunner.class) @PrepareForTest({ManagementFactory.class})

  2. 创建Mock MBeanServer类:

    MBeanServer mockMBeanServer = createMock(MBeanServer.class);

  3. 使用EasyMock创建Expetation:

    EasyMock.expect(ManagementFactory.getPlatformMBeanServer())。andReturn(mockMBeanServer);

  4. 在上面的代码中,我收到以下错误:

      

    java.lang.IllegalStateException:不兼容的返回值类型at   org.easymock.internal.MocksControl.andReturn(MocksControl.java:218)

    最后,经过多次尝试,我需要忽略这个类:

    @PowerMockIgnore( { 
        "org.apache.commons.logging.*", 
        "javax.management.*", 
    }) 
    

    我的测试用例正在运行,除了模拟和测试MBean类。还有更好的选择吗?

1 个答案:

答案 0 :(得分:0)

您似乎忽略了对mockStatic()的调用。您的测试方法将变为:

@Test
public void testMyBean() throws Exception {
  MBeanServer mockMBeanServer = createMock(MBeanServer.class);

  PowerMock.mockStatic(ManagementFactory.class);

  EasyMock.expect( ManagementFactory.getPlatformMBeanServer() )
    .andReturn(mockMBeanServer);
  //...
}

PowerMock有一些很好的文档涵盖了这个主题here