我可以将 OSGi Mock 与声明式服务注释一起使用吗

Can I use OSGi Mocks with Declarative Services Annotations

我正在尝试测试使用 Declaratice Services 注释 (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 元数据 class。

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 注释注释的 classes? OSGi Mocks 的文档 suggests that Declarative Services annotations is supported in version 2.0.0 and higher。我使用的版本符合这个标准。

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

当我用 Gradle 编译测试中的 class 时,'com.cognifide.aem.bundle' 插件用于生成 SCR 描述符并将其放置在生成的 Java 存档中。这就是 Gradle 执行的单元测试工作正常的原因。只需单击 IntelliJ 中的 运行 按钮就会导致此步骤被遗漏。

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

我转到 设置 > 构建、执行、部署 > Gradle > 运行ner 并使用下拉菜单,以便我可以决定是否在逐个测试的基础上使用 Gradle。