MBeanInstantiator { @PostConstruct public void registerSystemCommanderMBean() { final String contextName = contextNameProvider.getContextName(); final ObjectName objectName = commandMBeanNameProvider.create(contextName); if (!mbeanServer.isRegistered(objectName)) { register(objectName); } }  @PostConstruct void registerSystemCommanderMBean(); @PreDestroy void unregisterMBeans();  }
@Test public void shouldRegisterSystemCommanderMBean() throws Exception { final String contextName = "my-context"; final ObjectName objectName = mock(ObjectName.class, "mBeanName"); when(mbeanServer.isRegistered(objectName)).thenReturn(false); when(contextNameProvider.getContextName()).thenReturn(contextName); when(commandMBeanNameProvider.create(contextName)).thenReturn(objectName); mBeanInstantiator.registerSystemCommanderMBean(); verify(mbeanServer).registerMBean(systemCommander, objectName); verify(logger).info("Registering SystemCommander MBean using name 'mBeanName'"); }
@Test public void shouldNotRegisterSystemCommanderMBeanIfAlreadyRegistered() throws Exception { final String contextName = "my-context"; final ObjectName objectName = mock(ObjectName.class, "mBeanName"); when(contextNameProvider.getContextName()).thenReturn(contextName); when(commandMBeanNameProvider.create(contextName)).thenReturn(objectName); when(mbeanServer.isRegistered(objectName)).thenReturn(true); mBeanInstantiator.registerSystemCommanderMBean(); verify(mbeanServer, never()).registerMBean(systemCommander, objectName); verifyZeroInteractions(logger); }
@Test public void shouldThrowExceptionWhenMBeanRegisteringIncorrect() throws Exception { final MBeanRegistrationException mBeanRegistrationException = new MBeanRegistrationException(new NullPointerException("Ooops")); final String contextName = "my-context"; final ObjectName objectName = mock(ObjectName.class, "AnObjectName"); when(mbeanServer.isRegistered(objectName)).thenReturn(false); when(contextNameProvider.getContextName()).thenReturn(contextName); when(commandMBeanNameProvider.create(contextName)).thenReturn(objectName); doThrow(mBeanRegistrationException).when(mbeanServer).registerMBean(systemCommander, objectName); try { mBeanInstantiator.registerSystemCommanderMBean(); fail(); } catch (final ObjectNameException expected) { assertThat(expected.getCause(), is(mBeanRegistrationException)); assertThat(expected.getMessage(), is("Failed to register SystemCommander MBean using object name 'AnObjectName'")); } }