单元测试ServiceLoader [英] Unit test ServiceLoader

查看:148
本文介绍了单元测试ServiceLoader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 ServiceLoader 的方法来使用资源加载服务。

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;
}

我应该如何使用Junit对上述方法进行单元测试?

How should I unit test above method using Junit?

推荐答案

您需要将provider-configuration file复制到测试类目录中。

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

如何复制文件取决于您的构建工具(例如maven,gradle,ant,...)

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

作为maven的示例,您应该将它们存储在测试资源文件夹中。

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

src/test/resources/META-INF/services/your.package.ContextPlugin

这篇关于单元测试ServiceLoader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆