Junits for FrameworkUtil and BundleContext | Adobe Higher Education
Skip to main content
Level 3
January 23, 2023
Risolto

Junits for FrameworkUtil and BundleContext

  • January 23, 2023
  • 2 risposte
  • 1828 visualizzazioni

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

 

 

Questo argomento è stato chiuso alle risposte.
Migliore risposta di Peter_Puzanovs

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

2 risposte

Peter_Puzanovs
Community Advisor
Community Advisor
January 23, 2023

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

ParakhMaAutore
Level 3
January 23, 2023

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.

Peter_Puzanovs
Community Advisor
Community Advisor
January 23, 2023

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

Level 3
January 23, 2023