Mockito + PowerMock + TestNG + Libgdx - libgdx

I'm trying add the powermock library to the working project, but I'm getting errors.
How I add it:
1) AbsTest extends PowerMockTestCase
2) Build.gradle dependencies
3) In some test add #PrepareForTest({SomeClass.class}). After this step this error occured.
In build.gradle all libraries are included.
Error occured in a place where initialize HeadlessApplication for use Gdx.* static vars.
All tests in project extend this class:
abstract public class AbsTest extends PowerMockTestCase {
static {
initGdx();
}
protected static void initGdx() {
// Initialize libgdx headless for use static vars (e.g. Gdx.input.setInputProcessor)
final HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration();
config.renderInterval = 1f / 60; // Likely want 1f/60 for 60 fps
new HeadlessApplication(mock(Core.class), config); <=== ERROR LINE
}
#BeforeMethod(alwaysRun = true)
public void initMethod() throws Exception {
// Initialize mocks
MockitoAnnotations.initMocks(this);
}
}
Errors:
org.testng.TestNGException: An error occurred while instantiating
class ru.coolone.adventure_emulation.input.InputGroupsTest: null at
org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:435)
at
org.testng.internal.ClassHelper.createInstance(ClassHelper.java:336)
at
org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:125)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:190) at
org.testng.TestClass.getInstances(TestClass.java:95) at
org.testng.TestClass.initTestClassesAndInstances(TestClass.java:81)
at org.testng.TestClass.init(TestClass.java:73) at
org.testng.TestClass.(TestClass.java:38) at
org.testng.TestRunner.initMethods(TestRunner.java:389) at
org.testng.TestRunner.init(TestRunner.java:271) at
org.testng.TestRunner.init(TestRunner.java:241) at
org.testng.TestRunner.(TestRunner.java:167) at
org.testng.SuiteRunner$DefaultTestRunnerFactory.newTestRunner(SuiteRunner.java:663)
at org.testng.SuiteRunner.init(SuiteRunner.java:260) at
org.testng.SuiteRunner.(SuiteRunner.java:198) at
org.testng.TestNG.createSuiteRunner(TestNG.java:1271) at
org.testng.TestNG.createSuiteRunners(TestNG.java:1249) at
org.testng.TestNG.runSuitesLocally(TestNG.java:1107) at
org.testng.TestNG.runSuites(TestNG.java:1028) at
org.testng.TestNG.run(TestNG.java:996) at
org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72) at
org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:127)
Caused by: java.lang.ExceptionInInitializerError at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at
org.powermock.modules.testng.internal.TestClassInstanceFactory.create(TestClassInstanceFactory.java:51)
at
org.powermock.modules.testng.internal.PowerMockClassloaderObjectFactory.newInstance(PowerMockClassloaderObjectFactory.java:46)
at
org.powermock.modules.testng.PowerMockObjectFactory.newInstance(PowerMockObjectFactory.java:43)
at
org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:423)
... 21 more Caused by: java.lang.IllegalStateException: Could not
initialize plugin: interface org.mockito.plugins.MockMaker at
org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:66)
at com.sun.proxy.$Proxy19.isTypeMockable(Unknown Source) at
org.mockito.internal.util.MockUtil.typeMockabilityOf(MockUtil.java:29)
at
org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:22)
at
org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:186)
at
org.mockito.internal.creation.MockSettingsImpl.confirm(MockSettingsImpl.java:180)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:62) at
org.mockito.Mockito.mock(Mockito.java:1729) at
org.mockito.Mockito.mock(Mockito.java:1642) at
ru.coolone.adventure_emulation.AbsTest.initGdx(AbsTest.java:37) at
ru.coolone.adventure_emulation.AbsTest.(AbsTest.java:30) ...
29 more Caused by: java.lang.IllegalStateException: Failed to load
interface org.mockito.plugins.MockMaker implementation declared in
sun.misc.CompoundEnumeration#7dc3712 at
org.mockito.internal.configuration.plugins.PluginLoader.loadImpl(PluginLoader.java:101)
at
org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:45)
at
org.mockito.internal.configuration.plugins.PluginRegistry.(PluginRegistry.java:18)
at
org.mockito.internal.configuration.plugins.Plugins.(Plugins.java:17)
at org.mockito.internal.util.MockUtil.(MockUtil.java:24) ...
37 more Caused by: java.lang.ClassCastException: Cannot cast
org.powermock.api.mockito.mockmaker.PowerMockMaker to
org.mockito.plugins.MockMaker at
java.lang.Class.cast(Class.java:3369) at
org.mockito.internal.configuration.plugins.PluginLoader.loadImpl(PluginLoader.java:97)
... 41 more
build.gradle:
...
testCompile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
testCompile "com.badlogicgames.gdx:gdx-backend-headless:$gdxVersion"
testCompile 'org.testng:testng:6.13.1'
testCompile "org.mockito:mockito-core:2.8.9"
testCompile "org.powermock:powermock-api-mockito2:1.7.3"
testCompile "org.powermock:powermock-module-testng:1.7.3"
...

I'm fixed this. Im just move initGdx(); to overloaded beforePowerMockTestMethod() or beforePowerMockTestClass() and delete mockito annotations initialization because it execute in the parent class.
fixed AbsTest class:
abstract public class AbsTest extends PowerMockTestCase {
protected static void initGdx() {
// Initialize libgdx headless for use static vars (e.g. Gdx.input.setInputProcessor)
final HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration();
config.renderInterval = 1f / 60; // Likely want 1f/60 for 60 fps
new HeadlessApplication(mock(Core.class), config);
}
#BeforeMethod
#Override
protected void beforePowerMockTestMethod() throws Exception {
initGdx();
super.beforePowerMockTestMethod();
}
}
or with overload beforePowerMockTestClass method
abstract public class AbsTest extends PowerMockTestCase {
protected static void initGdx() {
// Initialize libgdx headless for use static vars (e.g. Gdx.input.setInputProcessor)
final HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration();
config.renderInterval = 1f / 60; // Likely want 1f/60 for 60 fps
new HeadlessApplication(mock(Core.class), config);
}
#BeforeClass
#Override
protected void beforePowerMockTestClass() throws Exception {
super.beforePowerMockTestClass();
initGdx();
}
}

Related

When use Spy and PowerMock together throws RuntimeException

When I use Spy annotation together with the PowerMock in my JUnit test case, it throws RuntimeException, but when I use Mock annotation together with the PowerMock, the test case is working fine.
Anybody able to advise about my issue?
This is my code
#RunWith(PowerMockRunner.class)
#PrepareForTest({DBConnectionPool.class})
#PowerMockIgnore("javax.management.*")
public class TestAbcController {
private static final Logger logger = Logger.getLogger(TestAbcController .class.getName());
public TestAbcController () {
}
#Spy
private SampleDao mockDao;
#InjectMocks
private AbcController ctr;
private BasicDataSource ds = null;
private MockMvc mockMvc;
#BeforeClass
public static void setUpClass() {
logger.setLevel(Level.INFO);
PowerMockito.mockStatic(DBConnectionPool.class);
PowerMockito.when(DBConnectionPool.getDataSource()).thenReturn(UnitTestDbConnection.getDataSource());
}
#Test
public void testMain() {
when(mockDao.getMap()).thenReturn(new HashMap());
}
Below is the detail of the exception
java.lang.RuntimeException: Invoking the beforeTestMethod method on
PowerMock test listener
org.powermock.api.extension.listener.AnnotationEnabler#d86a6f failed.
at
org.powermock.api.mockito.internal.configuration.PowerMockitoSpyAnnotationEngine.process(PowerMockitoSpyAnnotationEngine.java:53)
at
org.powermock.api.mockito.internal.configuration.PowerMockitoInjectingAnnotationEngine.process(PowerMockitoInjectingAnnotationEngine.java:32)
at
org.powermock.api.extension.listener.AnnotationEnabler.injectSpiesAndInjectToSetters(AnnotationEnabler.java:60)
at
org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:55)
at
org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:90)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:292)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at
org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at
org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at
org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at
org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at
org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
at
org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at
org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
I fixed this issue after I upgrade my mockito-core to 2.8.9 and powermock to 1.7.4

"java.lang.NullPointerException" when trying to click any element in a page

The code was running completely fine until yesterday. Now, when I am trying to run any test case, Selenium (using Java) throws java.lang.NullPointerException on the homepage itself. Below is a simple test case which is failing due to the error.
Below is my Test class which is calling the constructor of TestBase class and then, initializing the driver object. When the control goes into homepage.clickSearchLink() method, the test ends and error comes.
package com.ss.qa.testcases;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.*;
import com.ss.qa.base.TestBase;
import com.ss.qa.pages.HomePage;
import com.ss.qa.pages.SearchPage;
public class SearchPageTest extends TestBase{
HomePage homepage;
SearchPage searchpage;
SearchPageTest(){
super();
}
#BeforeMethod
public void setUp(){
initialization();
homepage = new HomePage();
searchpage = homepage.clickSearchLink();
}
#Test
public void verifyResultCount() {
int count = searchpage.countResults("a");
Assert.assertEquals(count, 15);
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
Below is my TestBase class which is calling the constructor of Test Base class and initializing the driver object
package com.ss.qa.base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Driver;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import com.ss.qa.util.TestUtil;
import com.ss.qa.util.WebEventListener;
public class TestBase {
public static WebDriver driver = null;
public static Properties prop;
public static EventFiringWebDriver e_driver;
public static WebEventListener eventListener;
public TestBase(){
try {
prop = new Properties();
FileInputStream ip = new FileInputStream("D:\\Users\\eclipse-
workspace\\src\\main\\java\\com\\ss\\qa\\config\\config.properties");
prop.load(ip);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void initialization() {
String browserName = prop.getProperty("browser");
if (browserName.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Downloads\\"chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
System.out.println("driver=" + driver);
}
else if (browserName.equalsIgnoreCase("FF")) {
System.setProperty("webdriver.gecko.driver", "C:\\Users\\Downloads\\geckodriver-v0.21.0-win64\\geckodriver.exe");
driver = new FirefoxDriver();
}
e_driver = new EventFiringWebDriver(driver);
eventListener = new WebEventListener();
e_driver.register(eventListener);
driver = e_driver;
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT , TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT , TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
}
}
<!-- Method in Event Listener class which is showing in error -->
public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
System.out.println("Find happened on " + arg1.toString() + " Using method " + arg0.toString());
}
ERROR LOG :
[RemoteTestNG] detected TestNG version 6.11.0 Starting ChromeDriver
2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e) on port 21677 Only local connections are allowed. log4j:WARN No appenders could be
found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly. log4j:WARN See
http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Sep 09, 2018 9:10:58 AM org.openqa.selenium.remote.ProtocolHandshake
createSession INFO: Detected dialect: OSS driver=ChromeDriver: chrome
on XP (ac62d0828d89443b9bedefa67a824225) Inside the afterNavigateTo to
https://www.ss.com/en FAILED CONFIGURATION: #BeforeMethod setUp
java.lang.NullPointerException at
com.ss.qa.util.WebEventListener.afterFindBy(WebEventListener.java:31)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564) at
org.openqa.selenium.support.events.EventFiringWebDriver$1.invoke(EventFiringWebDriver.java:81)
at com.sun.proxy.$Proxy9.afterFindBy(Unknown Source) at
org.openqa.selenium.support.events.EventFiringWebDriver.findElement(EventFiringWebDriver.java:189)
at
org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at
org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy12.isDisplayed(Unknown Source) at
com.ss.qa.pages.HomePage.clickSearchLink(HomePage.java:67) at
com.ss.qa.testcases.SearchPageTest.setUp(SearchPageTest.java:25) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564) at
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at
org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:523)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:224)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:599) at
org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869) at
org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193) at
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
at
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:744) at
org.testng.TestRunner.run(TestRunner.java:602) at
org.testng.SuiteRunner.runTest(SuiteRunner.java:380) at
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375) at
org.testng.SuiteRunner.privateRun(SuiteRunner.java:340) at
org.testng.SuiteRunner.run(SuiteRunner.java:289) at
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at
org.testng.TestNG.runSuitesSequentially(TestNG.java:1301) at
org.testng.TestNG.runSuitesLocally(TestNG.java:1226) at
org.testng.TestNG.runSuites(TestNG.java:1144) at
org.testng.TestNG.run(TestNG.java:1115) at
org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Kindly suggest.
WebEventListener.java:31: keep the null check, one of the elements you are using is throwing a null pointer exception.
If you can post the printed content of the WebEventListener.java on line 31, then we can better examine the problem. To do that, change this line:
public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
System.out.println("Find happened on " + arg1 + " Using method " + arg0);
}
As per you comment " When the control goes into homepage.clickSearchLink() method, the test ends and error comes."
check whether this method "homepage.clickSearchLink()" is returning searchpage instance.
the method should be
~public Searchpage clickSearchLink(){
//click on element to get search page
//Also check whether element is present on page or not.
return new Searchpage();
}~

Unable to autowire bean in Spring integration test

I am trying to autowire a bean for unit testing purpose.
I'm working with annotation based configuration classes and not using xml based application-context.
Porblem: It says Failed to load ApplicationContext
Here is my code.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = AppContextLoader.class, loader = AnnotationConfigContextLoader.class)
public class StockTest
{
static Logger logger = Logger.getLogger(StockTest.class);
#Autowired
private StockGenerator generator;
#Test
public void someTest()
{//some code here}
}
}
And my configuration class looks like this
#Configuration
public class AppContextLoader
{
#Bean
public StockGenerator stockProvider()
{
StockGenerator stock = new StockGenerator();
return stock;
}
}
Note: StockGenerator is spring managed so I am not sure how to handle it here. I am following this example.
Or is there any other way to autowire beans when one is not using xml based approach.

Multiple #Test method in a java class fails with java.lang.Exception: No runnable methods

I have multiple #Test method in a class while running the paxexam it fails with the below Exception
java.lang.Exception: No runnable methods
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:169)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:104)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:355)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:57)
at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.<init>(ContainerTestRunner.java:54)
at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunnerBuilder.runnerForClass(ContainerTestRunnerBuilder.java:48)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunnerClassRequest.getRunner(ContainerTestRunnerClassRequest.java:61)
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:31)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
The below is the pax exam code. When i run this code i get an exception. Adding one more point if i change this annotation #ExamReactorStrategy(PerClass.class) to #ExamReactorStrategy(PerMethod.class) this will work the problem is test container restarts after every method
#RunWith(PaxExam.class)
#ExamReactorStrategy(PerClass.class)
public class Integration5TestCases {
private static Logger LOG = LoggerFactory.getLogger(IntegrationTestCases.class);
#Inject
private BundleContext bc;
#Inject
protected FeaturesService featuresService;
/**
* To make sure the tests run only when the boot features are fully
* installed
*/
#Inject
BootFinished bootFinished;
#Configuration
public static Option[] configuration() throws Exception {
MavenUrlReference oracleLib = maven()
.groupId("com.oracle")
.artifactId("ojdbc6")
.version("11.2.0")
.type("jar");
MavenUrlReference dbHandler = maven().groupId("Oracle")
.artifactId("DBHandler")
.versionAsInProject()
.type("xml")
.classifier("features");
return new Option[] {
returnNewKarafInstance(),
systemProperty(PaxExamConstants.ORCALESYSPROPNAME).value(dbHandler.getURL()),
KarafDistributionOption.debugConfiguration("8898", true),
bootClasspathLibrary(oracleLib),
configureConsole().ignoreLocalConsole(),
logLevel(LogLevel.INFO),
keepRuntimeFolder(),
};
}
private static KarafDistributionBaseConfigurationOption returnNewKarafInstance(){
return karafDistributionConfiguration().frameworkUrl(maven().groupId("org.apache.karaf").artifactId("apache-karaf")
.type("zip").versionAsInProject())
.unpackDirectory(new File("target/paxexam/unpack/"))
.useDeployFolder(false);
}
#Inject
SessionFactory commandProcessor;
#Test
public void test1() throws Exception {
System.out.println("sd");
}
#Test
public void test2() throws Exception {
System.out.println("sd");
}
}
This was happening because junit lib was initialized twice inside the karaf container. Thanks for the help guys.

jodd cannot manage to inject two beans

I have a DAO and a Service class each implements a interface:
public interface TemperatureDao extends GenericDAO<TemperatureLog> {
public abstract List<TemperatureLog> getLastHourTemperatures();
}
#PetiteBean(value="temperatureDao",wiring=WiringMode.AUTOWIRE)
public class TemperatureDaoImpl extends GenericAbstractDAO<TemperatureLog> implements TemperatureDao {
#Override
public List<TemperatureLog> getLastHourTemperatures(){
//do stuff here
return temps;
}
}
and
public interface TemperatureService {
public abstract boolean save(TemperatureLog t);
public abstract List<TemperatureLog> getLastHoutTemperatures();
}
#PetiteBean(value="temperatureService",wiring=WiringMode.AUTOWIRE)
public class TemperatureServiceImpl extends GenericService implements TemperatureService {
#PetiteInject
private TemperatureDao temperatureDao;
public TemperatureDao getTemperatureDao() {
return temperatureDao;
}
public void setTemperatureDao(TemperatureDao temperatureDao) {
this.temperatureDao = temperatureDao;
}
#Override
public boolean save(TemperatureLog t){
try {
temperatureDao.saveOrUpdate(t);
return true;
}catch(Exception e) {
return false;
}
}
#Override
#Transaction(propagation = JtxPropagationBehavior.PROPAGATION_REQUIRED, readOnly = true,isolation=JtxIsolationLevel.ISOLATION_READ_COMMITTED)
public List<TemperatureLog> getLastHoutTemperatures(){
return temperatureDao.getLastHourTemperatures();
}
}
and the problem is that temperatureDao is not injected as i get NullPointerException here:
return temperatureDao.getLastHourTemperatures();
The logs looks fine to me :
127 [DEBUG] j.p.PetiteBeans.registerPetiteBean:244 - Registering bean: temperatureDao of type: TemperatureDaoImpl in: SingletonScope using wiring mode: AUTOWIRE
128 [DEBUG] j.p.ProxettaBuilder.process:187 - processing: ro/videanuadrian/smartHome/dao/impl/TemperatureDaoImpl
128 [DEBUG] j.p.ProxettaBuilder.define:228 - proxy not applied ro.videanuadrian.smartHome.dao.impl.TemperatureDaoImpl
134 [DEBUG] j.p.PetiteBeans.registerPetiteBean:244 - Registering bean: temperatureService of type: TemperatureServiceImpl in: SingletonScope using wiring mode: AUTOWIRE
135 [DEBUG] j.p.ProxettaBuilder.process:187 - processing: ro/videanuadrian/smartHome/services/impl/TemperatureServiceImpl
139 [DEBUG] j.p.ProxettaBuilder.define:243 - proxy created ro.videanuadrian.smartHome.services.impl.TemperatureServiceImpl
So, any idea what I'm I missing here?
I am posting new answer to explain better what is going on.
What happens here is that you have proxy created on TemperatureServiceImpl and registered it as a PetiteBean, which is perfectly correct :) So, Petite container gets the proxified class, which is a subclass of your service implementation.
When Petite does the wiring, it is scanning the proxy class and, therefore, it can not see the annotated private field in the super class (which is the original TemperatureServiceImpl).
You can fix this in two ways:
either by removing private modifier (and use anything else) - than container will 'see' the field in the subclass, or
simply annotating the e.g. getTemperatureDao() method with #PetiteInject and leaving the field as it is.
Hope this explains what is going on. I will try to address this in upcoming 3.6 release.
Solved, the issue was that temperatureDao was declared as private. I have change it to default and now it works.