Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

Mock BundleContext using Junit5

Avatar

Level 2

Hi All,
I have a generic method which is used for rendering a service reference.

 

shafali12_0-1685596850167.png

Can you guide me how can I create a Junit test method for the same?
When trying to mock BundleContext getting error as shown below:
Cannot invoke "org.osgi.framework.Bundle.getBundleContext()" because the return value of "org.osgi.framework.FrameworkUtil.getBundle(java.lang.Class)" is null

 

 

@arunpatidar @RohanGarg @MayurSatav @rawvarun @aanchal-sikka @ManviSharma @Pulkit_Jain_ @Jörg_Hoh @kautuk_sahni 

 

 

 

 

1 Accepted Solution

Avatar

Correct answer by
Employee Advisor

Hi,

 

To create a JUnit test method for a generic method that renders a service reference, use mocking frameworks like Mockito or PowerMockito to mock the required dependencies such as BundleContext.

 

When encountering the error "Cannot invoke org.osgi.framework.Bundle.getBundleContext() because the return value of org.osgi.framework.FrameworkUtil.getBundle(java.lang.Class) is null," mock the FrameworkUtil.getBundle(Class) method and specify a non-null return value to resolve the issue.

View solution in original post

3 Replies

Avatar

Correct answer by
Employee Advisor

Hi,

 

To create a JUnit test method for a generic method that renders a service reference, use mocking frameworks like Mockito or PowerMockito to mock the required dependencies such as BundleContext.

 

When encountering the error "Cannot invoke org.osgi.framework.Bundle.getBundleContext() because the return value of org.osgi.framework.FrameworkUtil.getBundle(java.lang.Class) is null," mock the FrameworkUtil.getBundle(Class) method and specify a non-null return value to resolve the issue.

Avatar

Level 2

Hi @ManviSharma,

Tried mocking as commented above:

shafali12_0-1685938551908.png


Even after mocking the FrameworkUtil.getBundle(Class), I am still getting below error:

 

org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

 


Thanks