OSGi Service ClassCastException с JUnit и Maven SurefireJAVA

Программисты JAVA общаются здесь
Anonymous
OSGi Service ClassCastException с JUnit и Maven Surefire

Сообщение Anonymous »

В модуле demo-api-interface у меня есть интерфейс DemoInterfacePrinter:

Код: Выделить всё

public interface DemoInterfacePrinter {
void printVersion();
}
В модуле demo-api у меня есть фактическая реализация DemoInterfacePrinter и активатор OSGi:

Код: Выделить всё

public class OsgiActivator implements BundleActivator {
public void start(BundleContext context) {
try {
Log.writeToFile("Registering service.");
DemoInterfacePrinter service = new DemoInterfacePrinterImpl();
service.printVersion();
context.registerService(DemoInterfacePrinter.class.getName(), service, null);
Log.writeToFile("Service registered successfully.");
} catch (Exception e) {
Log.writeToFile("Error registering service: " + e.getMessage());
}
}

public void stop(BundleContext context) {
// Service is automatically unregistered
}
}
Pom.xml этого демонстрационного API показан ниже, я упаковал его как пакет:

Код: Выделить всё

    


org.apache.felix
maven-bundle-plugin
4.2.1
true


${pom.groupId}.${pom.artifactId}
${pom.name}
${pom.version}-->
org.example.OsgiActivator
org.example.service





А в модуле thrid у меня есть тест, который пытается проверить зарегистрированный пакет OSGi:

Код: Выделить всё

public class ContextTest {
@Test
public void test1() throws BundleException, InterruptedException, InvalidSyntaxException {
// Load the OSGi framework factory
FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
Map config = new HashMap();
config.put("org.osgi.framework.storage.clean", "onFirstInit");
// Set the OSGi configuration as needed

// Create and start the OSGi framework
Framework framework = frameworkFactory.newFramework(config);
framework.start();

// Load the bundle
Bundle bundle = context.installBundle("file:/xxx/demo-api/target/demo-api-1.0.0.jar");
bundle.start();

// get the bundle context of the bundle
BundleContext bundleContext = bundle.getBundleContext();
// get DemoInterfacePrinter service
ServiceReference ref = bundleContext.getServiceReference(DemoInterfacePrinter.class.getName());
DemoInterfacePrinter service = (DemoInterfacePrinter) context.getService(ref);
service.printVersion();
}
}
Но вот я получил:

Код: Выделить всё

java.lang.ClassCastException: class org.example.DemoInterfacePrinterImpl cannot be cast to class org.example.service.DemoInterfacePrinter (org.example.DemoInterfacePrinterImpl is in unnamed module of loader org.apache.felix.framework.BundleWiringImpl$BundleClassLoader @4d465b11; org.example.service.DemoInterfacePrinter is in unnamed module of loader 'app')
Я использую Maven Surefire для запуска теста: mvn test -Dtest=ContextTest.
Похоже, ошибка связана с тем, что DemoInterfacePrinter Класс загружается Surefire через загрузчик системных классов, а служба загружается загрузчиком классов пакета OSGi.
Но если я хочу напрямую выполнить приведение класса в этом тесте с помощью Maven Surefire , как я могу это сделать?
Я ценю любую полезную информацию.

Подробнее здесь: https://stackoverflow.com/questions/784 ... n-surefire

Вернуться в «JAVA»