Mock BundleContext using Junit5 | Community
Skip to main content
Level 2
June 1, 2023
Solved

Mock BundleContext using Junit5

  • June 1, 2023
  • 2 replies
  • 2585 views

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

 

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_ @joerghoh @kautuk_sahni 

 

 

 

 

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

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.

2 replies

ManviSharma
Adobe Employee
ManviSharmaAdobe EmployeeAccepted solution
Adobe Employee
June 1, 2023

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.

shafali12Author
Level 2
June 5, 2023

Hi @manvisharma,

Tried mocking as commented above:


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