Code Coverage for OSGI Configuration

Published
Custom OSGi configurations are often required based on project needs. In a previous article, we discussed how to implement custom OSGi configurations. Now, we will cover how to write unit tests and ensure code coverage for these configurations using JUnit 5, OSGi Mocks, and Mockito.
Before writing unit tests, ensure you have required dependencies in pom.xml file. These dependencies include osgi-mock.junit5 for mocking OSGi services and mockito for dependency injection.
pom.xml
<dependency> <groupId>org.apache.sling</groupId> <artifactId>org.apache.sling.testing.osgi-mock.junit5</artifactId> <version>3.5.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>5.15.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>5.15.2</version> <scope>test</scope> </dependency>
For this tutorial, we will use an example OSGi configuration service from another article. You can refer this page for full implementation details.
We use OsgiContext from org.apache.sling.testing.osgi-mock.junit5 to test our service implementation. The following unit test will ensure that OSGi configurations are correctly read and applied in AEM projects, providing proper test coverage.
AppConfigServiceImplTest.java
@ExtendWith(OsgiContextExtension.class) public class AppConfigServiceImplTest { @Test public void testAppConfigService(OsgiContext osgiContext) { Map<String, Object> properties = new HashMap<>(); properties.put("app.name", "aem-demo"); properties.put("api.endpoint", "https://www.google.com"); properties.put("client.id", "XXX"); properties.put("client.secret", "ZZZ"); AppConfigService appConfigService = osgiContext.registerInjectActivateService( new AppConfigServiceImpl(), properties); Assertions.assertEquals("aem-demo", appConfigService.getAppName()); Assertions.assertEquals("https://www.google.com", appConfigService.getAPIEndpoint()); Assertions.assertEquals("XXX", appConfigService.getClientId()); Assertions.assertEquals("ZZZ", appConfigService.getClientSecret()); } }
If you have implemented it using a different approach, let's discuss.
Write your Comment