0

I need to mock following code:

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

I am usign PowerMock to mock ManagementFactory with following code snippet:

  1. At class level, I configured:

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

  2. Create Mock MBeanServer class:

    MBeanServer mockMBeanServer = createMock(MBeanServer.class);

  3. create Expetation using EasyMock:

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

In above code, I am getting following error:

java.lang.IllegalStateException: incompatible return value type at org.easymock.internal.MocksControl.andReturn(MocksControl.java:218)

Finally, after tried a lot, I need to ignore this class:

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

My test cases are working, except mocking and testing MBean classes. Any better option?

arviarya
  • 650
  • 9
  • 9

1 Answers1

0

It looks like you left out the call to mockStatic(). Your test method would become:

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

  PowerMock.mockStatic(ManagementFactory.class);

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

PowerMock has some great documentation covering this topic here.

Matt Lachman
  • 4,541
  • 3
  • 30
  • 40