如何访问Pax Exam测试探针包中的资源?

时间:2016-03-04 12:15:19

标签: java osgi jbossfuse pax-exam

我正在使用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考试中加载资源?如何检查资源是否包含在测试探针包中?

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:1)

Jérémie提出的解决方案工作得很好:
this.getClass().getClassLoader().getResourceAsStream("/myresource");

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

将文件移动到正确的文件夹中后,可以通常的方式将它们作为资源进行访问。

相关问题