junit 使用自定义注射器测试吊索模型时出现的问题

ojsjcaue  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(109)

我一直在为一个项目做一些吊索模型的工作,并在这个过程中创建了几个自定义的注入器。当实现(在AEM中使用)时,一切似乎都工作得很好。但是,当我测试自定义的注入器时,它们并没有运行。
这是我目前设置的一个示例

在我的模型中

@Inheritable
@CustomAnnotation("foo")
private String _foo

测试中(使用wcm.io模拟库进行测试)

@Rule
AemContext context = new AemContext(ResourceResolverType.RESOURCERESOLVER_MOCK);

//required by the injector
@Mock
InheritanceService _inheritanceService;

@Mock
InheritableInjector _inheritanceInjector;

@Before
public void setup() {
    context.registerService(InheritanceService.class, _inheritanceService);
    context.registerService(InheritableInjector.class, _inheritanceInjector);

    context.addModelsForPackage("com.package.example.models");

    //use this resource in tests to adaptTo(MyModel.class)
    _resource = context.load().json("myJson.json", "/myPath");
}

... tests

测试编译并运行,但是注入器没有被执行。我知道它被注册了,因为当我没有在上下文中注册注入器的依赖服务时,我会得到一个错误。当我调试它时,未命中任何断点。我想知道是否还需要注册“Inheritable”注解的地方,或者如果有人只是有任何关于如何让自定义注入器执行的一般信息。
谢谢你

yws3nbqq

yws3nbqq1#

我能够弄清楚我的错误。所以关于Sling模型注入器需要记住的重要一点是,它们只是OSGI服务(我完全让自己远离的东西)。
因此,为了修复错误,我需要做的就是像对待普通服务一样对待它们,然后记住用@InjectMocks注解Injector。
下面的代码现在很好用。

@Mock
InheritanceService _inheritanceService; //injector dependency

@InjectMocks
InheritanceInjector _inheritanceInjector;

@Before
public void setup() {
    context.registerService(InheritanceService.class, _inheritanceService);
    context.registerService(InheritableInjector.class, _inheritanceInjector);
}

希望这对任何可能遇到这个问题的人都有帮助。如果有人能让这个答案更好,请随时回复/编辑。

相关问题