Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

@reference in Unit Tests

Avatar

Level 4

Hello, hopefully the last question this week.

I inject my Service in the servlet with:

@Reference
IRssFeed rssFeed;

The question is now how to do it with AEM Context.

@Test
public void testDoGetForJson() throws IOException, WCMException {

   context.registerService(IRssFeed.class, new RssFeedImpl());

}

I also tried the other ways, but the rssFeed is always null.

// register OSGi service

context.registerService(MyClass.class, myService);

// or alternatively: inject dependencies, activate and register OSGi service

context.registerInjectActivateService(myService);

At first step I added the maven-build plugin to my pom.xml but afterwards i get some errors for old testcases:

<plugin>
  <groupId>org.apache.felix</groupId>
  <artifactId>maven-bundle-plugin</artifactId>
  <version>3.3.0</version>
  <extensions>true</extensions>
  <executions>
  <execution>
  <id>scr-metadata</id>
  <goals>
  <goal>manifest</goal>
  </goals>
  </execution>
  </executions>
  <configuration>
  <exportScr>true</exportScr>
  <instructions>
  <Embed-Dependency>
   mailjet-client,

  http-client-java,

  solr-solrj,

  zookeeper,

  gson,

  rome,

  rome-utils,

  jdom2

   </Embed-Dependency>
  <Export-Package>
   com.test.aem.relaunch.*,net.tanesha.recaptcha,net.tanesha.recaptcha.http

   </Export-Package>
  <Import-Package>
   javax.inject;version=0.0.0,

  *;resolution:=optional

   </Import-Package>
  <Sling-Model-Packages>com.test.aem.relaunch.*</Sling-Model-Packages>
  <_dsannotations>*</_dsannotations>
   <!-- Enable processing of OSGI metatype annotations -->
   <_metatypeannotations>*</_metatypeannotations>
   <!--<_plugin>org.apache.felix.scrplugin.bnd.SCRDescriptorBndPlugin;destdir=${project.build.outputDirectory};</_plugin>-->
   </instructions>
  </configuration>
</plugin>

This is one example of the errors appeared after adding the plugin:

java.lang.RuntimeException: Unable to read classpath resource: OSGI-INF/metatype/com.test.aem.relaunch.schedulers.JobSearchScheduler.xml

at org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.toXmlDocument(OsgiMetadataUtil.java:230)

at org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.parseMetadataDocument(OsgiMetadataUtil.java:194)

at org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.parseMetadataDocuments(OsgiMetadataUtil.java:183)

at org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.initMetadataDocumentCache(OsgiMetadataUtil.java:171)

at org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.<clinit>(OsgiMetadataUtil.java:114)

at org.apache.sling.testing.mock.osgi.MapMergeUtil.propertiesMergeWithOsgiMetadata(MapMergeUtil.java:73)

at org.apache.sling.testing.mock.osgi.MapMergeUtil.propertiesMergeWithOsgiMetadata(MapMergeUtil.java:55)

at org.apache.sling.testing.mock.osgi.MockBundleContext.registerService(MockBundleContext.java:120)

at org.apache.sling.testing.mock.osgi.MockBundleContext.registerService(MockBundleContext.java:108)

at org.apache.sling.testing.mock.osgi.MockBundleContext.<init>(MockBundleContext.java:81)

at org.apache.sling.testing.mock.osgi.MockOsgi.newBundleContext(MockOsgi.java:50)

at org.apache.sling.testing.mock.osgi.ComponentContextBuilder.build(ComponentContextBuilder.java:69)

at org.apache.sling.testing.mock.osgi.MockOsgi.newComponentContext(MockOsgi.java:67)

at org.apache.sling.testing.mock.osgi.context.OsgiContextImpl.componentContext(OsgiContextImpl.java:74)

at org.apache.sling.testing.mock.osgi.context.OsgiContextImpl.bundleContext(OsgiContextImpl.java:83)

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:141)

at org.apache.sling.testing.mock.osgi.context.OsgiContextImpl.registerDefaultServices(OsgiContextImpl.java:66)

at org.apache.sling.testing.mock.osgi.context.OsgiContextImpl.setUp(OsgiContextImpl.java:47)

at org.apache.sling.testing.mock.sling.context.SlingContextImpl.setUp(SlingContextImpl.java:103)

at io.wcm.testing.mock.aem.context.AemContextImpl.setUp(AemContextImpl.java:74)

at io.wcm.testing.mock.aem.junit.AemContext.access$100(AemContext.java:48)

at io.wcm.testing.mock.aem.junit.AemContext$1.before(AemContext.java:156)

at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:46)

at org.junit.rules.RunRules.evaluate(RunRules.java:20)

at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)

at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)

at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)

at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)

at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)

at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)

at org.junit.runners.ParentRunner.run(ParentRunner.java:363)

at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)

at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)

at org.junit.runner.JUnitCore.run(JUnitCore.java:137)

at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)

at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)

at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)

at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by: org.xml.sax.SAXParseException; Premature end of file.

at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)

at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)

at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121)

at org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.toXmlDocument(OsgiMetadataUtil.java:226)

... 40 more

if I use this:

IRssFeed rssFeed = new RssFeedImpl();
MockOsgi.injectServices(rssFeed, bundleContext);
MockOsgi.activate(rssFeed,bundleContext);

The error message change to:

org.apache.sling.testing.mock.osgi.NoScrMetadataException: No OSGi SCR metadata found for class com.test.aem.relaunch.services.rss.RssFeedImpl

I thought the maven plugin will create it for me?

So is there any other way to inject the reference? Or someone sees a mistake?

13 Replies

Avatar

Level 4

Here is my pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
  <groupId>com.test.aem</groupId>
  <artifactId>test-com-relaunch</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <relativePath>../pom.xml</relativePath>
  </parent>
  <artifactId>test-com-relaunch.core</artifactId>
  <packaging>bundle</packaging>
  <name>test-com-relaunch - core</name>
  <description>Core bundle for test-relaunch</description>
  <properties>
  <app.bundle-embed-dependency>gson;inline=true;</app.bundle-embed-dependency>
  <jacoco.outputDir>${project.build.directory}</jacoco.outputDir>
  <jacoco.out.ut.file>jacoco-ut.exec</jacoco.out.ut.file>
  <sonar.jacoco.reportPath>${jacoco.outputDir}/coverage-reports/${jacoco.out.ut.file}

   </sonar.jacoco.reportPath>
  </properties>
  <build>
  <plugins>
  <plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.7.9</version>
  <executions>
  <execution>
  <id>pre-unit-test</id>
  <goals>
  <goal>prepare-agent</goal>
  </goals>
  <configuration>
  <destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
  <propertyName>surefireArgLine</propertyName>
  </configuration>
  </execution>
  <execution>
  <id>post-unit-test</id>
  <phase>test</phase>
  <goals>
  <goal>report</goal>
  </goals>
  <configuration>
  <dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
  <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
  </configuration>
  </execution>
  </executions>
  </plugin>

  <plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-failsafe-plugin</artifactId>
  </plugin>
  <plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  </plugin>
   <!--<plugin>-->
  <!--<groupId>org.apache.felix</groupId>-->
  <!--<artifactId>maven-scr-plugin</artifactId>-->
  <!--<version>1.24.0</version>-->
  <!--</plugin>-->
   <plugin>
  <groupId>org.apache.felix</groupId>
  <artifactId>maven-bundle-plugin</artifactId>
  <version>3.3.0</version>
  <extensions>true</extensions>
  <executions>
  <execution>
  <id>scr-metadata</id>
  <goals>
  <goal>manifest</goal>
  </goals>
  </execution>
  </executions>
  <configuration>
  <exportScr>true</exportScr>
  <instructions>
  <Embed-Dependency>
   mailjet-client,

  http-client-java,

  solr-solrj,

  zookeeper,

  gson,

  rome,

  rome-utils,

  jdom2

   </Embed-Dependency>
  <Export-Package>
   com.test.aem.relaunch.*,net.tanesha.recaptcha,net.tanesha.recaptcha.http

   </Export-Package>
  <Import-Package>
   javax.inject;version=0.0.0,

  *;resolution:=optional

   </Import-Package>
  <Sling-Model-Packages>com.test.aem.relaunch.*</Sling-Model-Packages>
  <_dsannotations>*</_dsannotations>
   <!-- Enable processing of OSGI metatype annotations -->
   <_metatypeannotations>*</_metatypeannotations>
   <!--<_plugin>org.apache.felix.scrplugin.bnd.SCRDescriptorBndPlugin;destdir=${project.build.outputDirectory};</_plugin>-->
   </instructions>
  </configuration>
  </plugin>
  <plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.18.1</version>
  <configuration>
  <argLine>${surefireArgLine}</argLine>
  <useSystemClassLoader>true</useSystemClassLoader>
  <includes>
  <include>**/Test*.java</include>
  <include>**/*Test.java</include>
  <include>**/*TestCase.java</include>
  </includes>
  <testSourceDirectory>src/test/java</testSourceDirectory>
  <properties>
  <property>
  <name>listener</name>
  <value>org.sonar.java.jacoco.TestNGListener</value>
  </property>
  </properties>
  </configuration>
  </plugin>
  <plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>cobertura-maven-plugin</artifactId>
  <version>2.7</version>
  <configuration>
  <instrumentation>
  <excludes>
  <exclude>com/test/aem/relaunch/beans/*.class</exclude>
  <exclude>com/test/aem/relaunch/config/*.class</exclude>
  <exclude>com/test/aem/relaunch/constants/*.class</exclude>
  <exclude>com/test/aem/relaunch/exceptions/*.class</exclude>
  <exclude>com/test/aem/relaunch/services/*.class</exclude>
  <exclude>com/test/aem/relaunch/package-info.class</exclude>
  <exclude>de/beesite/wsdl_test/beecomteste_test/services/DBSuche/*.class</exclude>
  <exclude>com/test/aem/relaunch/models/sitemap/*.class</exclude>
  <exclude>com/test/aem/relaunch/adapters/*.class</exclude>
  <exclude>com/test/aem/relaunch/adapters/*.class</exclude>
  <exclude>com/test/aem/relaunch/models/NavigationController.class</exclude>
  <exclude>com/test/aem/relaunch/models/PagePropertiesComponent.class</exclude>
  <exclude>com/test/aem/relaunch/models/HeaderController.class</exclude>
  <exclude>com/test/aem/relaunch/models/SiteUtils.class</exclude>
  <exclude>com/test/aem/relaunch/models/FooterDeController.class</exclude>
  <exclude>com/test/aem/relaunch/models/RedirectPage.class</exclude>
  <exclude>com/test/aem/relaunch/servlets/RequestServlet.class</exclude>
  <exclude>com/test/aem/relaunch/models/PrimaryLinksFooterController.class</exclude>
  <exclude>com/test/aem/relaunch/models/SecondaryLinksFooterController.class</exclude>
  </excludes>
  </instrumentation>
  </configuration>
  </plugin>
  </plugins>
  </build>
  <dependencies>
  <dependency>
  <groupId>org.jacoco</groupId>
  <artifactId>org.jacoco.agent</artifactId>
  <classifier>runtime</classifier>
  <scope>test</scope>
  <version>0.7.9</version>
  </dependency>
  <dependency>
  <groupId>org.sonarsource.java</groupId>
  <artifactId>sonar-jacoco-listeners</artifactId>
  <version>3.8</version>
  <scope>test</scope>
  </dependency>
  <dependency>
  <groupId>org.apache.felix</groupId>
  <artifactId>org.apache.felix.scr</artifactId>
  
  </dependency>
  <dependency>
  <groupId>org.apache.felix</groupId>
  <artifactId>org.apache.felix.scr.bnd</artifactId>
  
  </dependency>
   <!-- OSGi Dependencies -->
   <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  </dependency>
  <dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  </dependency>
  <dependency>
  <groupId>com.test.aem</groupId>
  <artifactId>integration-testing-tools</artifactId>
  </dependency>
  <dependency>
  <groupId>org.apache.sling</groupId>
  <artifactId>org.apache.sling.testing.tools</artifactId>
  </dependency>
  <dependency>
  <groupId>org.apache.sling</groupId>
  <artifactId>org.apache.sling.junit.core</artifactId>
  </dependency>
  <dependency>
  <groupId>org.apache.sling</groupId>
  <artifactId>org.apache.sling.junit.scriptable</artifactId>
  </dependency>
  <dependency>
  <groupId>org.apache.sling</groupId>
  <artifactId>org.apache.sling.junit.remote</artifactId>
  </dependency>
  <dependency>
  <groupId>com.adobe.aem</groupId>
  <artifactId>uber-jar</artifactId>
  <version>6.2.0</version>
  <classifier>apis</classifier>
  <scope>provided</scope>
  </dependency>
  <dependency>
  <groupId>com.test.aem</groupId>
  <artifactId>test-aem-foundation.core</artifactId>
  <version>1.1.43</version>
  <scope>provided</scope>z

   </dependency>
   <!-- needed for javax.Inject in AEM6.2 -->
   <dependency>
  <groupId>org.apache.felix</groupId>
  <artifactId>org.apache.felix.scr.annotations</artifactId>
  </dependency>
  <dependency>
  <groupId>biz.aQute</groupId>
  <artifactId>bndlib</artifactId>
  </dependency>
  <dependency>
  <groupId>org.osgi</groupId>
  <artifactId>osgi.core</artifactId>
  <version>6.0.0</version>
  <scope>provided</scope>
  </dependency>
  <dependency>
  <groupId>org.osgi</groupId>
  <artifactId>org.osgi.compendium</artifactId>
  </dependency>
   <!-- Other Dependencies -->
   <dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  </dependency>

  <dependency>
  <groupId>javax.jcr</groupId>
  <artifactId>jcr</artifactId>
  </dependency>
  <dependency>
  <groupId>javax.inject</groupId>
  <artifactId>javax.inject</artifactId>
  <version>1</version>
  </dependency>
  <dependency>
  <groupId>com.adobe.aem</groupId>
  <artifactId>aem-api</artifactId>
  </dependency>
  <dependency>
  <groupId>org.apache.sling</groupId>
  <artifactId>org.apache.sling.models.api</artifactId>
  </dependency>
  <dependency>
  <groupId>org.apache.sling</groupId>
  <artifactId>org.apache.sling.models.impl</artifactId>
  </dependency>
  <dependency>
  <groupId>com.turbomanage.basic-http-client</groupId>
  <artifactId>http-client-java</artifactId>
  <version>0.89</version>
  </dependency>
  <dependency>
  <groupId>com.mailjet</groupId>
  <artifactId>mailjet-client</artifactId>
  <version>4.0.6-SNAPSHOT</version>
  <exclusions>
  <exclusion>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-io</artifactId>
  </exclusion>
  </exclusions>
  </dependency>

  <dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-all</artifactId>
  <version>1.10.19</version>
  </dependency>
  <dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-module-junit4</artifactId>
  <version>1.7.1</version>
  <scope>test</scope>
  </dependency>
  <dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-api-mockito</artifactId>
  <version>1.7.1</version>
  </dependency>
  <dependency>
  <groupId>io.wcm</groupId>
  <artifactId>io.wcm.testing.aem-mock</artifactId>
  <version>2.2.8</version>
  <scope>test</scope>
  </dependency>
  <dependency>
  <groupId>org.apache.sling</groupId>
  <artifactId>org.apache.sling.testing.sling-mock-oak</artifactId>
  <version>2.0.2</version>
  <scope>test</scope>
  </dependency>

  <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
  </dependency>
  <dependency>
  <groupId>junit-addons</groupId>
  <artifactId>junit-addons</artifactId>
  <version>1.4</version>
  <scope>test</scope>
  </dependency>
   <!-- https://mvnrepository.com/artifact/org.apache.sling/org.apache.sling.testing.osgi-mock -->
   <dependency>
  <groupId>org.apache.sling</groupId>
  <artifactId>org.apache.sling.testing.osgi-mock</artifactId>
  <version>2.3.4</version>
  <scope>test</scope>
  </dependency>

  <dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  </dependency>
  <dependency>
  <groupId>commons-logging</groupId>
  <artifactId>commons-logging</artifactId>
  </dependency>
  <dependency>
  <groupId>org.apache.avalon.framework</groupId>
  <artifactId>avalon-framework-api</artifactId>
  </dependency>
  <dependency>
  <groupId>logkit</groupId>
  <artifactId>logkit</artifactId>
  </dependency>
  <dependency>
  <groupId>javax.jms</groupId>
  <artifactId>jms</artifactId>
  </dependency>
  <dependency>
  <groupId>com.day.commons</groupId>
  <artifactId>day-commons-any</artifactId>
  </dependency>

  <dependency>
  <groupId>org.apache.sling</groupId>
  <artifactId>org.apache.sling.testing.sling-mock</artifactId>
  <version>2.2.14</version>
  <scope>test</scope>
  </dependency>

  <dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  </dependency>
  <dependency>
  <groupId>io.wcm</groupId>
  <artifactId>io.wcm.testing.junit-commons</artifactId>
  </dependency>
  <dependency>
  <groupId>org.jsoup</groupId>
  <artifactId>jsoup</artifactId>
  </dependency>
  <dependency>
  <groupId>org.jmockit</groupId>
  <artifactId>jmockit</artifactId>
  <version>1.34</version>
  </dependency>
  <dependency>
  <groupId>com.google.code.findbugs</groupId>
  <artifactId>jsr305</artifactId>
  <version>3.0.0</version>
  </dependency>
  <dependency>
  <groupId>org.testng</groupId>
  <artifactId>testng</artifactId>
  <version>6.8.8</version>
  </dependency>
  <dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20090211</version>
  </dependency>
  <dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  </dependency>
  <dependency>
  <groupId>net.tanesha.recaptcha4j</groupId>
  <artifactId>recaptcha4j</artifactId>
  <version>0.0.7</version>
  </dependency>
  <dependency>
  <groupId>org.apache.axis</groupId>
  <artifactId>axis</artifactId>
  <version>1.4</version>
  <scope>compile</scope>
  </dependency>
  <dependency>
  <groupId>org.apache.axis</groupId>
  <artifactId>axis-jaxrpc</artifactId>
  <version>1.4</version>
  <scope>compile</scope>
  </dependency>
  <dependency>
  <groupId>org.apache.axis</groupId>
  <artifactId>axis-saaj</artifactId>
  <version>1.4</version>
  <scope>compile</scope>
  </dependency>
  <dependency>
  <groupId>wsdl4j</groupId>
  <artifactId>wsdl4j</artifactId>
  <version>1.6.2</version>
  <scope>compile</scope>
  </dependency>
  <dependency>
  <groupId>commons-discovery</groupId>
  <artifactId>commons-discovery</artifactId>
  <version>0.2</version>
  <scope>compile</scope>
  </dependency>
  <dependency>
  <groupId>javax.xml</groupId>
  <artifactId>jaxrpc-api</artifactId>
  <version>1.1</version>
  </dependency>
  <dependency>
  <groupId>javax.mail</groupId>
  <artifactId>mail</artifactId>
  <version>1.4.1</version>
  </dependency>
  <dependency>
  <groupId>javax.activation</groupId>
  <artifactId>activation</artifactId>
  <version>1.1</version>
  </dependency>
  <dependency>
  <groupId>commons-lang</groupId>
  <artifactId>commons-lang</artifactId>
  <version>2.6</version>
  </dependency>
  <dependency>
  <groupId>org.apache.solr</groupId>
  <artifactId>solr-solrj</artifactId>
  <version>5.3.0</version>
  </dependency>
  <dependency>
  <groupId>javax.xml.stream</groupId>
  <artifactId>stax-api</artifactId>
  <version>1.0-2</version>
  </dependency>
  <dependency>
  <groupId>com.rometools</groupId>
  <artifactId>rome</artifactId>
  <version>1.8.0</version>
  </dependency>
  <dependency>
  <groupId>com.rometools</groupId>
  <artifactId>rome-utils</artifactId>
  <version>1.8.0</version>
  </dependency>
  <dependency>
  <groupId>org.jdom</groupId>
  <artifactId>jdom2</artifactId>
  <version>2.0.6</version>
  </dependency>
  </dependencies>
</project>

Avatar

Level 10

Is this null when you use it in a normal service?

@Reference
IRssFeed rssFeed;

Avatar

Level 4

It works when deployed to an aem instance. It just don't get injected during the test.

And its also in the context after doing:

IRssFeed rssFeed = new RssFeedImpl();

context.registerService(rssFeed);

1360819_pastedImage_0.png

Avatar

Level 10

In the Archetype 11 generated test - we see @inject working.

/*

*  Copyright 2015 Adobe Systems Incorporated

*

*  Licensed under the Apache License, Version 2.0 (the "License");

*  you may not use this file except in compliance with the License.

*  You may obtain a copy of the License at

*

*      http://www.apache.org/licenses/LICENSE-2.0

*

*  Unless required by applicable law or agreed to in writing, software

*  distributed under the License is distributed on an "AS IS" BASIS,

*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

*  See the License for the specific language governing permissions and

*  limitations under the License.

*/

package com.foo.core.models;

import static org.junit.Assert.assertNotNull;

import static org.junit.Assert.assertTrue;

import static org.mockito.Mockito.mock;

import static org.mockito.Mockito.when;

import java.util.UUID;

import junitx.util.PrivateAccessor;

import org.apache.sling.settings.SlingSettingsService;

import org.junit.Before;

import org.junit.Test;

/**

* Simple JUnit test verifying the HelloWorldModel

*/

public class TestHelloWorldModel {

    //@Inject

    private HelloWorldModel hello;

   

    private String slingId;

   

    @Before

    public void setup() throws Exception {

        SlingSettingsService settings = mock(SlingSettingsService.class);

        slingId = UUID.randomUUID().toString();

        when(settings.getSlingId()).thenReturn(slingId);

        hello = new HelloWorldModel();

        PrivateAccessor.setField(hello, "settings", settings);

        hello.init();

    }

   

    @Test

    public void testGetMessage() throws Exception {

        // some very basic junit tests

        String msg = hello.getMessage();

        assertNotNull(msg);

        assertTrue(msg.length() > 0);

    }

}

You should generated a Maven 11 project and see if @Inject (to your service) works:

Creating an Adobe Experience Manager 6.3 Project using Adobe Maven Archetype 11

Avatar

Level 4

I think it's something wrong in the pom.xml

When I do this:

IRssFeed rssFeed = new RssFeedImpl();
context.registerInjectActivateService(rssFeed);

I got this error, so the plugin does not work correctly and does not create the manifest for it.

1232 [main] INFO org.apache.jackrabbit.oak.plugins.index.IndexUpdate - Found a new index node [reference]. Reindexing is requested

1239 [main] INFO org.apache.jackrabbit.oak.plugins.index.IndexUpdate - Reindexing will be performed for following indexes: [/oak:index/slingResourceType, /oak:index/slingAlias, /oak:index/uuid, /oak:index/slingVanityPath, /oak:index/slingResource, /oak:index/jcrLanguage, /oak:index/reference, /oak:index/jcrLockOwner, /oak:index/nodetype]

1517 [main] INFO org.apache.jackrabbit.oak.plugins.index.IndexUpdate - Indexing report

    - /oak:index/nodetype*(1238)

1762 [main] INFO org.apache.jackrabbit.oak.plugins.index.IndexUpdate - Reindexing will be performed for following indexes: [/oak:index/principalName, /oak:index/authorizableId, /oak:index/acPrincipalName]

1780 [main] INFO org.apache.jackrabbit.oak.plugins.index.IndexUpdate - Indexing report

    - /oak:index/principalName*(2)

    - /oak:index/authorizableId*(2)

2698 [main] INFO org.apache.sling.jcr.resource.internal.helper.jcr.JcrResourceProvider - Detected Oak based repository. Using improved JCR Resource Listener with observation queue length 1000

8858 [main] INFO org.apache.sling.jcr.resource.internal.helper.jcr.JcrResourceProvider - Detected Oak based repository. Using improved JCR Resource Listener with observation queue length 1000

org.apache.sling.testing.mock.osgi.NoScrMetadataException: No OSGi SCR metadata found for class com.test.aem.relaunch.services.rss.RssFeedImpl

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:141)

at com.test.aem.relaunch.servlets.rssfeed.RssFeedServletTest.testDoGetForJson(RssFeedServletTest.java:74)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.lang.reflect.Method.invoke(Method.java:498)

at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)

at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)

at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)

at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)

at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)

at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)

at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)

at org.junit.rules.RunRules.evaluate(RunRules.java:20)

at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)

at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)

at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)

at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)

at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)

at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)

at org.junit.runners.ParentRunner.run(ParentRunner.java:363)

at org.junit.runner.JUnitCore.run(JUnitCore.java:137)

at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)

at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)

at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)

at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Avatar

Level 10

Did you try building an Adobe Maven 11 Archetype and using the default test class a starting point. Then you can see the test results in the C:\AdobeCQ\AEM633\core\target\surefire-reports. (AEM633 my project name)

Avatar

Level 10

I did a small test using Maven 11 generated project. I wrote a small interface:

package com.foo.core;

public interface Foo {

   

   

    public String getName();

}

Imple class:

package com.foo.core;

import org.osgi.service.component.annotations.Component;

@Component

public class FooImpl implements Foo{

   

    public String getName()

    {

        return "Scott" ;

    }

}

Now i want to test this to make sure getName returns a value. IN the TestHelloWorldModel class - i setup a second test --

package com.foo.core.models;

import static org.junit.Assert.assertNotNull;

import static org.junit.Assert.assertTrue;

import static org.mockito.Mockito.mock;

import static org.mockito.Mockito.when;

import java.util.UUID;

import junitx.util.PrivateAccessor;

import org.apache.sling.settings.SlingSettingsService;

import org.junit.Before;

import org.junit.Test;

import com.foo.core.Foo;

import com.foo.core.FooImpl;

/**

* Simple JUnit test verifying the HelloWorldModel

*/

public class TestHelloWorldModel {

    //@Inject

    private HelloWorldModel hello;

  

    private Foo myFoo;

  

    private String slingId;

  

    

    @Before

    public void setup() throws Exception {

        SlingSettingsService settings = mock(SlingSettingsService.class);

        slingId = UUID.randomUUID().toString();

        when(settings.getSlingId()).thenReturn(slingId);

        hello = new HelloWorldModel();

        PrivateAccessor.setField(hello, "settings", settings);

        hello.init();

      

        myFoo = new FooImpl();

      

    }

  

    @Test

    public void testGetMessage() throws Exception {

        // some very basic junit tests

        String msg = hello.getMessage();

        assertNotNull(msg);

        assertTrue(msg.length() > 0);

    

    

    }

  

    @Test

    public void testFooMessage() throws Exception {

     

        //custom service

        String msgFoo = myFoo.getName() ;

        assertNotNull(msgFoo);

        assertTrue(msgFoo.length() > 0);

    }

}

Now my report file is stating 2 tests completed successfully:

-------------------------------------------------------------------------------

Test set: com.foo.core.models.TestHelloWorldModel

-------------------------------------------------------------------------------

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.692 s - in com.foo.core.models.TestHelloWorldModel

Follow that way to test your classes and methods.

As you can see - we are following the same testing pattern as how the model class named HelloWorldModel is tested.

As you can see - they did not use @Refenence or @Inject in the example code. Test still runs fine.

Avatar

Level 4

Hi, I think you have misunderstood me.I want to inject the RSSImpl inside the servlet not in the test.

@Slf4j
public class RssFeedServlet extends SlingSafeMethodsServlet {

   @Reference
   IRssFeed rssFeed;
  private final SimpleDateFormat ISO_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
  private String serverName;

}

Avatar

Level 10

Based on your comment here - "It works when deployed to an aem instance. It just don't get injected during the test"

I thought you wanted to use dependency injection during a test.  The @Reference annotation works in a Sling Servlet.

This works in a Servlet -

@SlingServlet(paths="/bin/mySearchServlet", methods = "POST", metatype=true)

public class HandleClaim extends org.apache.sling.api.servlets.SlingAllMethodsServlet {

     private static final long serialVersionUID = 2598426539166789515L;

     

     @Reference

     private DataSourcePool source;

Avatar

Level 4

Yes I know it works, but the question is how to inject the Reference during unit tests?

@Test
public void testDoGetForJson() throws IOException, WCMException {

  IRssFeed rssFeed = new RssFeedImpl();
   context.registerInjectActivateService(rssFeed);
   context.requestPathInfo().setSelectorString("rss");
   context.requestPathInfo().setExtension("xml");
   context.currentPage("/content/de/ueber-uns/presse/press-releases");
   rssFeedServlet.doGet(context.request(), context.response());

}

Then I get this error:

org.apache.sling.testing.mock.osgi.NoScrMetadataException: No OSGi SCR metadata found for class

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:141)

at com.test.aem.relaunch.servlets.rssfeed.RssFeedServletTest.testDoGetForJson(RssFeedServletTest.java:73)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.lang.reflect.Method.invoke(Method.java:498)

at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)

at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)

at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)

at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)

at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)

at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)

at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)

at org.junit.rules.RunRules.evaluate(RunRules.java:20)

at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)

at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)

at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)

at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)

at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)

at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)

at org.junit.runners.ParentRunner.run(ParentRunner.java:363)

at org.junit.runner.JUnitCore.run(JUnitCore.java:137)

at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)

at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)

at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)

at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Avatar

Level 1

Hi Tim,

do you need the context?

IRssFeed rssFeed = mock(IRssFeed.class);

PrivateAccessor.setField(myService, "rssFeed", rssFeed);

works within my unit tests for @Reference injected services.

Best regards

Kristina