SLING-10479 - throw IllegalStateException if registration is already unregistered
diff --git a/core/src/main/java/org/apache/sling/testing/mock/osgi/MockBundleContext.java b/core/src/main/java/org/apache/sling/testing/mock/osgi/MockBundleContext.java
index 2b17c95..3949585 100644
--- a/core/src/main/java/org/apache/sling/testing/mock/osgi/MockBundleContext.java
+++ b/core/src/main/java/org/apache/sling/testing/mock/osgi/MockBundleContext.java
@@ -190,9 +190,13 @@
}
void unregisterService(MockServiceRegistration<?> registration) {
- this.registeredServices.remove(registration);
- handleRefsUpdateOnUnregister(registration, this);
- notifyServiceListeners(ServiceEvent.UNREGISTERING, registration.getReference());
+ boolean wasRemoved = this.registeredServices.remove(registration);
+ if (wasRemoved) {
+ handleRefsUpdateOnUnregister(registration, this);
+ notifyServiceListeners(ServiceEvent.UNREGISTERING, registration.getReference());
+ } else {
+ throw new IllegalStateException("Service was already unregistered");
+ }
}
@SuppressWarnings("null")
diff --git a/core/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextTest.java b/core/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextTest.java
index 293cd8c..8ca1be7 100644
--- a/core/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextTest.java
+++ b/core/src/test/java/org/apache/sling/testing/mock/osgi/MockBundleContextTest.java
@@ -37,6 +37,7 @@
import java.util.List;
import org.junit.After;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -233,6 +234,13 @@
reg1.unregister();
assertNull(bundleContext.getServiceReference(clazz1));
+
+ try {
+ reg1.unregister();
+ Assert.fail("Unregistering a non existant service should throw IllegalStateException");
+ } catch (IllegalStateException e) {
+ assertEquals("Service was already unregistered", e.getMessage());
+ }
}