我目前正在尝试使用 PAX-EXAM+KARAF 编写 OSGI 集成测试,但遇到了一个问题,即 pax 考试试图在依赖包在容器中实际启动/初始化之前执行测试方法。奇怪的是,有时测试会成功,在这种情况下,所有的包/上下文都会启动并记录下来,但大多数时候它不会。方法的延迟无济于事:(任何人都可以帮助解决这个问题吗?
我正在使用 PAX-EXAM 2.6.0、org.apache.karaf.tooling.exam.container 2.3.0、apache-karaf 2.3.0。
代码:
@Inject
BundleContext bundleContext;
@Inject
EntityManagerFactoryService entityManagerFactoryService;//Service exposed trough OSGI
protected EntityManager entityManager;
@Before
public void init() throws InterruptedException {
entityManager = entityManagerFactoryService.getEntityManagerFactory().createEntityManager();
}
@Configuration
public static Option[] configuration() throws Exception {
return new Option[] {
karafDistributionConfiguration().frameworkUrl(maven().groupId("org.apache.karaf").artifactId("apache-karaf").type("zip").versionAsInProject())
.karafVersion("2.3.0").name("Apache Karaf"),
mavenBundle("com.google.guava", "guava", "13.0.1").startLevel(30),
mavenBundle("com.mysql.jdbc", "com.springsource.com.mysql.jdbc", "5.1.6").startLevel(30),
mavenBundle("javax.persistence", "com.springsource.javax.persistence", "2.0.0").startLevel(30),
mavenBundle("org.apache.commons", "com.springsource.org.apache.commons.lang", "2.6.0").startLevel(30),
...the rest of bundles
junitBundles(), };
测试方法:
@Test
public void contextNotNull() {
Assert.assertNotNull(entityManagerFactoryService);
}
日志:
java.lang.ClassNotFoundException: com.startjg.crp.core.dao.service.EntityManagerFactoryService not found by PAXEXAM-PROBE-749fa717-8bdc-4d9a-9803-bdaf6d4edac0 [144]
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1460)
at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:72)
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1843)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
完整日志: https ://www.dropbox.com/s/v12r15sbmtu9svp/log.txt
也尝试过没有运气:
protected <T> Object getService(Class<T> serviceClass) {
int maxCount = 5;
int delay = 5000;
for (int i = 0; i <= maxCount; i++) {
if (bundleContext.getServiceReference(serviceClass) != null) {
ServiceReference<T> serviceReference = bundleContext.getServiceReference(serviceClass);
return bundleContext.getService(serviceReference);
} else {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return null;
}
@Before
public void init() throws InterruptedException {
EntityManagerFactoryService emfs = (EntityManagerFactoryService) getService(EntityManagerFactoryService.class);
entityManager = entityManagerFactoryService.getEntityManagerFactory().createEntityManager();
}