Junits for FrameworkUtil and BundleContext | Community
Skip to main content
Level 3
Jan 23, 2023 9:21 AM UTC
Solved

Junits for FrameworkUtil and BundleContext

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

 

 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Peter_Puzanovs
Peter_PuzanovsAccepted solution
New Participant
Jan 23, 2023 11:52 AM UTC

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

4 replies

Level 3
Jan 23, 2023 12:29 PM UTC
Peter_Puzanovs
New Participant
Jan 23, 2023 10:21 AM UTC

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

Translate
ParakhMaAuthor
Level 3
Jan 23, 2023 10:26 AM UTC

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.

Translate
Peter_Puzanovs
Peter_PuzanovsAccepted solution
New Participant
Jan 23, 2023 11:52 AM UTC

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

Translate