【问题标题】:Can I use OSGi Mocks with Declarative Services Annotations我可以将 OSGi 模拟与声明式服务注释一起使用吗
【发布时间】:2018-11-05 01:53:30
【问题描述】:

我正在尝试测试使用声明服务注释 (org.osgi.service.component.annotations) 进行注释的 OSGi 服务。我已经根据AEM Multi-Project Example 生成了我的项目。

public class PostServiceTest {

  @Rule
  public AemContext context = new AemContext((AemContextCallback) context -> {
    context.registerInjectActivateService(new PostService());
  }, ResourceResolverType.RESOURCERESOLVER_MOCK);

  @Test
  public void shouldFetchRandomPosts() {
    final PostService postsService = context.getService(PostService.class);
    final List<Post> posts = postsService.randomPosts(100);

    assertEquals(100, posts.size());
  }

}

每当我在 IntelliJ 中运行此测试时,OSGi Mocks 都会抱怨测试类中缺少 SCR 元数据。

org.apache.sling.testing.mock.osgi.NoScrMetadataException: No OSGi SCR metadata found for class com.example.PostServiceTest
  at org.apache.sling.testing.mock.osgi.OsgiServiceUtil.injectServices(OsgiServiceUtil.java:381)
  at org.apache.sling.testing.mock.osgi.MockOsgi.injectServices(MockOsgi.java:148)
  at org.apache.sling.testing.mock.osgi.context.OsgiContextImpl.registerInjectActivateService(OsgiContextImpl.java:153)
  at org.apache.sling.testing.mock.osgi.context.OsgiContextImpl.registerInjectActivateService(OsgiContextImpl.java:168)
  at com.example.PostServiceTest.shouldReturnTheEnpointNamesWithValidConfigurationAsTheListOfAcceptableKeys(PostServiceTest.java:23)

这是否意味着我只能测试使用 Apache Felix 附带的旧 SCR 注释注释的类? OSGi Mocks suggests that Declarative Services annotations is supported in version 2.0.0 and higher 的文档。我使用的版本符合这个标准。

【问题讨论】:

  • 如果您将 BND 插件与 Gradle 一起使用,这可能会对您有所帮助(您必须针对 Gradle 进行调整):felix.apache.org/documentation/faqs/…
  • @Jens Gradle 插件确实会生成元数据。我的问题源于IDE在编译测试源时不会这样做。将编译委托给 Gradle 就可以了。

标签: gradle intellij-idea junit osgi aem


【解决方案1】:

有趣的是,这只发生在我直接从 IDE 运行测试时。事实证明,在编译我的测试类时,IntelliJ 没有生成 SCR 元数据。

当我使用 Gradle 编译被测类时,'com.cognifide.aem.bundle' 插件用于生成 SCR 描述符并将其放置在生成的 Java 存档中。这就是 Gradle 执行的单元测试可以正常工作的原因。只需单击 IntelliJ 中的 Run 按钮,就会错过这一步。

为了让它工作,我最终设置了 IntelliJ 以允许我通过 Gradle 运行单元测试。

我去了 Settings > Build, Execution, Deployment > Gradle > Runner 并使用下拉菜单,以便我可以决定是否在逐个测试的基础上使用 Gradle。

【讨论】:

    猜你喜欢
    • 2013-10-09
    • 1970-01-01
    • 2021-10-05
    • 2012-04-27
    • 2011-05-27
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多