MBeanInstantiator { @PreDestroy public void unregisterMBeans() { final String contextName = contextNameProvider.getContextName(); final ObjectName objectName = commandMBeanNameProvider.create(contextName); if (mbeanServer.isRegistered(objectName)) { unregister(objectName); } }  @PostConstruct void registerSystemCommanderMBean(); @PreDestroy void unregisterMBeans();  }
@Test public void shouldUnregisterMBeans() throws Exception { final String contextName = "my-context"; final ObjectName objectName = mock(ObjectName.class, "mBeanName"); when(mbeanServer.isRegistered(objectName)).thenReturn(true); when(contextNameProvider.getContextName()).thenReturn(contextName); when(commandMBeanNameProvider.create(contextName)).thenReturn(objectName); mBeanInstantiator.unregisterMBeans(); verify(mbeanServer).unregisterMBean(objectName); verify(logger).info("Unregistering SystemCommander MBean using name 'mBeanName'"); }
@Test public void shouldNotUnregisterMBeansIfNotAlreadyRegistered() 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.unregisterMBeans(); verify(mbeanServer, never()).unregisterMBean(objectName); verifyZeroInteractions(logger); }
@Test public void shouldThrowExceptionWhenMBeanUnregisteringIncorrect() 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(true); when(contextNameProvider.getContextName()).thenReturn(contextName); when(commandMBeanNameProvider.create(contextName)).thenReturn(objectName); doThrow(mBeanRegistrationException).when(mbeanServer).unregisterMBean(objectName); try { mBeanInstantiator.unregisterMBeans(); fail(); } catch (final ObjectNameException expected) { assertThat(expected.getCause(), is(mBeanRegistrationException)); assertThat(expected.getMessage(), is("Failed to unregister MBean with object name 'AnObjectName'")); } }