Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

JUNIT Test case for OSGI Service

Avatar

Level 3

Hi Team,

Need help in writing junit for below osgi service's activate method and get resourceResolver method.

@Component(

label="xyz",

description = "xyz",

immediate=true,

metatype=true,

name="myservice")

@Service("MyService.class)

public class MyServiceImpl implements MyService

{

String path="";

@Activate

public void activate(Map<String, Object) properties)

{

ConfigurationParameters cfp = ConfigurationParameters.of(properties);

path = cfp.getConfigValue("jcrPath", "defaultPath");

}

public ResourceResolver getResourceResolver()

{

Map<String, Object) param = new HashMap<String,Object>();

param.put(ResourceResolverFactory.SUBSERVICE,SERVICE_IDENTIFIER);

ResourceResolver resolver = null;

resolver = resourceResolverFactory.getServiceResourceResolver(param);

return resolver;

}

public String getPath()

{

return path;

}

3 Replies

Avatar

Community Advisor

Dear Sir or Madam,

If you posted valid Java code it would help you writing JUnit test.

With this Java code it's impossible to write a JUnit test, as there is no resourceResolverFactory to mock.

Regards,

Peter

Avatar

Level 3

Sorry i forgot to add,

ResourceResolverFactory at class level, I have updated code below,

@Component(

label="xyz",

description = "xyz",

immediate=true,

metatype=true,

name="myservice")

@Service("MyService.class)

public class MyServiceImpl implements MyService

{

@Reference

ResourceResolverFactory  resourceResolverFactory ;

String SERVICE_IDENTIFIER = "myServiceIdentfier";

String path="";

@Activate

public void activate(Map<String, Object) properties)

{

ConfigurationParameters cfp = ConfigurationParameters.of(properties);

path = cfp.getConfigValue("jcrPath", "defaultPath");

}

public ResourceResolver getResourceResolver()

{

Map<String, Object) param = new HashMap<String,Object>();

param.put(ResourceResolverFactory.SUBSERVICE,SERVICE_IDENTIFIER);

ResourceResolver resolver = null;

resolver = resourceResolverFactory.getServiceResourceResolver(param);

return resolver;

}

public String getPath()

{

return path;

}

Avatar

Level 10

When you create a Maven Archetype project - a test class is set up for you. Have you looked at modifying that code to meet your needs.  We have many articles too that describe how to use code like this:

Map<String, Object) param = new HashMap<String,Object>();

param.put(ResourceResolverFactory.SUBSERVICE,SERVICE_IDENTIFIER);

ResourceResolver resolver = null;

resolver = resourceResolverFactory.getServiceResourceResolver(param);