Expand my Community achievements bar.

July 31st AEM Gems Webinar: Elevate your AEM development to master the integration of private GitHub repositories within AEM Cloud Manager.
SOLVED

Junits for FrameworkUtil and BundleContext

Avatar

Level 4

We have a common Utility class, which has following method 

public static ResourceResolver getServiceResourceResolver(String subServiceName){

       final BundleContext bundleContext = FrameworkUtil.getBundle(Util.class).getBundleContext();
       final ServiceReference factoryReference = bundleContext
                                                                          .getServiceReference(ResourceResolverFactory.class.getName());
       final ResourceResolverFactory resolverFactory = (ResourceResolverFactory) bundleContext
                                                                                     .getService(factoryReference);

       final Map<String, Object> map = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE,
                                                             (Object) serviceName);
-       return resolverFactory.getServiceResourceResolver(map);

}

 

This common Utility returns the resolver for AEMService : 

resolver = Util.getServiceResourceResolver("user");

 

While writing Junits for the AEMService, the resolver is always null, because JUnit tests run in a plain JVM with no OSGi Framework. Therefore there is no BundleContext available.

 

How do we write Junit for the AEMService.java

 

 

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi Mahesp,

 

Either rewrite Util to make into Mickito.Mockable unit or you can include other libs to mock static methods such as PowerMock.

 

Regards,

Peter

View solution in original post

4 Replies

Avatar

Community Advisor

Dear Maheshp,

 

Wonderful Sling project has already build a helpful utility library called OSGi mocks[1].

 

You may wish to utilise OSGi mock's to register ServiceReference and execute steps necessary to get to the actual tests.

 

[Apache Sling :: OSGi Mocks]

 

Regards,

Peter

Avatar

Level 4

The bundleContext reference is part of static method, and mockito 3.3 doesnt allow mocking of static methods.

Any higher version of mockito is not compatible with aemContext.

 

Can you elaborate more please, it will help us.

Avatar

Correct answer by
Community Advisor

Hi Mahesp,

 

Either rewrite Util to make into Mickito.Mockable unit or you can include other libs to mock static methods such as PowerMock.

 

Regards,

Peter