【问题标题】:How to access resources in Pax Exam test probe bundle?如何访问 Pax Exam 测试探针包中的资源?
【发布时间】:2016-06-18 04:12:36
【问题描述】:

我正在使用 Pax Exam 4.8、junit4、JBoss Fuse 作为 OSGi 容器为一些 OSGi 包开发集成测试。假设标准 Maven 设置。

容器启动,我的包已部署并正确启动。

现在在我的测试代码中,我需要加载资源并将其内容写入文件。 如果我理解正确,单元测试会自动部署为测试探针包。

@RunWith(PaxExam.class)
@ExamReactorStrategy(PerMethod.class)
public class ExampleTest {

    @javax.inject.Inject
    BundleContext bundleContext;

    @Configuration
    public Option[] config() throws Exception {
        // container setup
    }

    @Test
    public void testThatApplicationProcessesThisFile() {
        InputStream is1 = getClass().getResourceAsStream("myResource");  // returns null

        Bundle probeBundle = bundleContext.getBundle("local");
        InputStream is2 = probeBundle.getResource("myResource").openStream();
        // getResource() returns null

        // write the resource as a file
    }

}

如何在 Pax Exam 测试中加载资源?如何检查资源是否包含在测试探针包中?

【问题讨论】:

    标签: java osgi jbossfuse pax-exam


    【解决方案1】:

    您是否尝试过“简单”的 getResourceAsStream() ?这应该有效:

    this.getClass().getClassLoader().getResourceAsStream("/myresource");
    

    在我的集成测试的旧部分中,我使用以下函数来获取“prob”捆绑包(但老实说,我认为现在没有必要):

    private Bundle getProbeBundle() {
        for (Bundle bundle : bundleContext.getBundles()) {
            if (bundle.getSymbolicName().startsWith("PAXEXAM-PROBE-")) {
                return bundle;
            }
        }
        return null;
    }
    

    然后:

    getProbeBundle().getResource(from).openStream()
    

    【讨论】:

      【解决方案2】:

      Jérémie 提出的解决方案运行良好:
      this.getClass().getClassLoader().getResourceAsStream("/myresource");

      我的问题出在设置上。我把我的资源放在src/main/resources 文件夹中。在构建探测包时,Pax Exam 似乎只包含 src/test/resources 文件夹中的资源。

      将文件移动到正确的文件夹后,就可以像往常一样作为资源访问了。

      【讨论】:

        猜你喜欢
        • 2013-02-10
        • 1970-01-01
        • 2015-09-25
        • 2013-11-19
        • 1970-01-01
        • 2014-03-17
        • 2012-04-29
        • 2015-01-12
        • 2016-03-19
        相关资源
        最近更新 更多