Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test ServiceLoader

Tags:

java

I have a method that uses ServiceLoader to load services using resources.

public List<String> getContextData(int Id)
{
  List<String> list = new ArrayList<String>();
  ServiceLoader<ContextPlugin> serviceLoader =  ServiceLoader.load(ContextPlugin.class);
  for (Iterator<ContextPlugin> iterator = serviceLoader.iterator(); iterator.hasNext();)
  {
    list .addAll(iterator.next().getContextData(Id));
  }
  return list;
}

How should I unit test above method using Junit?

like image 770
Prabhath Avatar asked Mar 23 '15 07:03

Prabhath


1 Answers

You need to copy the "provider-configuration file" into your test class directory.

assuming your test class files are located at

test/classes/

you need to copy the "provider-configuration file" to

test/classes/META-INF/services/your.package.ContextPlugin

How to copy the files depend on your build tool (e.g. maven, gradle, ant, ...)

As example for maven you should store them in the test resources folder.

src/test/resources/META-INF/services/your.package.ContextPlugin
like image 76
SubOptimal Avatar answered Nov 15 '22 14:11

SubOptimal