Junit for getting Configuration through Bundle Context | Community
Skip to main content
Level 2
November 17, 2021

Junit for getting Configuration through Bundle Context

  • November 17, 2021
  • 2 replies
  • 1880 views

I am trying to write Junit using Junit5

 

@Mock
ProcessingComponentConfiguration config;

@Mock
FrameworkUtil framework;

@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
}

@Mock
ConfigurationAdmin configAdmin;

@Mock
ProcessingContext context;

@Mock
BundleContext bundleContext;

@Mock
SlingHttpServletRequest request;

@2785667
void testInit() throws IOException {
Mockito.when(context.getRequest()).thenReturn(request);
Mockito.when( request.getServerName()).thenReturn("server");
Mockito.when(framework.getBundle(Test.class).getBundleContext()).thenReturn(bundleContext);

}

 

It is giving null pointer exception when I inspect framework.getBundle(Test.class).getBundleContext().

 

How to write Junit for this. Below is my code.

 

BundleContext bundleContext = FrameworkUtil.getBundle(Test.class).getBundleContext();
ServiceReference slingSettingRef = bundleContext.getServiceReference(SlingSettingsService.class.getName());
SlingSettingsService slingSetting = (SlingSettingsService) bundleContext.getService(slingSettingRef);
ServiceReference factoryRef = bundleContext.getServiceReference(ConfigurationAdmin.class.getName());
ConfigurationAdmin configAdmin = (ConfigurationAdmin) bundleContext.getService(factoryRef);

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

2 replies

joerghoh
Adobe Employee
Adobe Employee
November 20, 2021

I recommend you to use the AEM Mocks library; it provides you mock implementations for the OSGI basics and there you can create tests much more easily and convenient.

 

I wrote some blog posts about it, you can find them here: https://cqdump.joerghoh.de/tag/unittest/

Level 2
May 30, 2023

Hi @joerghoh 
If we don't want to change the original codebase is there still any way to mock Bundle Context?

 

joerghoh
Adobe Employee
Adobe Employee
June 8, 2023

of course you can do that, but I think the benefit is large, especially because you don't need to rewrite all tests at once. But you can start with using the Sling Mocks / AEM Mocks when you need to create tests.

To your case: You probably need to mock each single step:

@Mock Bundle myBundle; @test void testInit() throws IOException { Mockito.when(context.getRequest()).thenReturn(request); Mockito.when( request.getServerName()).thenReturn("server"); Mockito.when(framework.getBundle(eq(Test.class).thenReturn(myBundle); Mockito.when(myBundle.getBundleContext()).thenReturn(bundleContext);
Level 2
May 30, 2023

@gazzalm54335496  Did you find a fix for this problem?