@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'"));
    }
}