Mocking Sample – ManagementFactory

Some time back I was googling to do mocking on my JMX layer. Day was out of luck, google servers were not able to read my mind. I tried different combinations to get help on my issue, but all that hardship lead me to think again for simple JMX Management Factory test case.

Code to be tested:

        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        final ObjectName oname = new ObjectName("com.package:type=Summary");
        final String[] databases = (String[])mbs.getAttribute(oname, "Databases");
        for (final String database : databases) {
             final CompositeData compositeData = (CompositeData)mbs.invoke(oname, "getDatabaseStatus", 
                          new Object[] { database }, new String[] { String.class.getName() });
              ...//some functional code

My mocking finally:

@PowerMockIgnore(value = { "*", "ObjectName.class" })
public class MockedClass {
     MBeanServer mbs = createMock(MBeanServer.class);
     ObjectName oname = PowerMock.createMockAndExpectNew(ObjectName.class, objectName);
     final String[] databases = new String[] { "Alpha", "Beta" };
     expect(mbs.getAttribute(oname, "Databases")).andReturn(databases);
     final CompositeData mockCompositeData = createMock(CompositeData.class);
     // Add expectation as per logic
     for (final String database : databases) {
            expect(mbs.invoke(isA(ObjectName.class), isA(String.class), cmp(new Object[] { database }, 
                         new Comparator<Object[]>() {
                public int compare(Object[] params1, Object[] params2) {
                   if ((params1 != null) && (params2 != null)) {
                        assertEquals("Size of passing parameters should be same", params1.length, 
                   return 0; 
            }, LogicalOperator.EQUAL), cmp(new String[] { String.class.getName() }, 
                         new Comparator<String[]>() {
                public int compare(String[] params1, String[] params2) {
                    if ((params1 != null) && (params2 != null)) {
                        assertEquals("Size of signature  should be same", params1.length, params2.length);                        }
                    return 0;
            }, LogicalOperator.EQUAL))).andReturn(mockCompositeData);
        PowerMock.replayAll(mbs, mockCompositeData);

        // System under test
        // Call test method


One Response to Mocking Sample – ManagementFactory

  1. A Joseph says:

    Helpful, thanks,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: