尝试使用 JUnit 和 tycho-surefire-plugin 测试 OSGi 服务。
插件的配置
<plugin>
<groupId>org.eclipse.tycho</groupId>
<artifactId>tycho-surefire-plugin</artifactId>
<version>${tycho.version}</version>
<configuration>
<showEclipseLog>true</showEclipseLog>
<dependencies>
<dependency>
<type>p2-installable-unit</type>
<artifactId>org.eclipse.equinox.ds</artifactId>
</dependency>
</dependencies>
</configuration>
</plugin>
测试用例(省略记录语句等)。测试类包含在它自己的 OSGi 包中,与被测代码分开。
@Component(name = "LdapConnectionConfigurationServiceTest", immediate = true)
public class LdapConnectionConfigurationServiceTest {
private LdapConnectionConfiguration testObject;
@Reference
public void bindTestObject(final LdapConnectionConfiguration testObject) {
this.testObject = testObject;
}
public void unbindTestObject(final LdapConnectionConfiguration testObject) {
this.testObject = null;
}
@Test
public void testLdapPort() {
assertEquals(10389, testObject.getLdapPort());
}
}
Tycho 启动一个 OSGi 容器,即测试包,启动LdapConnectionConfigurationServiceTest
服务并正确注入 testObject。
随后 JUnit 运行这个测试用例,但是创建这个类的另一个实例。哪个没有注入 testObject,所以我得到了 NullPointerExceptions。
不知道我错过了什么......我想要的是针对 OSGi 框架提供的注入服务运行测试用例。