I'm trying to do a unit test on my socket server code. I'm using Mockito but it blows up when the SUT runs to the following line because this is a final method.
socketChannel.register()
I'm new to PowerMock and I am trying to use it but I am facing various issues no matter what I tried. If someone can help review the following and offer some help that'd be great.
Here is the code used for testing.
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.IObjectFactory;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
#ActiveProfiles("QuickTest")
#Component
#ContextConfiguration(classes = AppConfigQuickTest.class)
#PrepareForTest({SocketChannel.class, QuickTest.class})
public class QuickTest extends AbstractTestNGSpringContextTests {
// An error occurred while instantiating class com.QuickTest: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
// Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
// at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:71)
// at org.apache.logging.log4j.LogManager.<clinit>(LogManager.java:60)
// at com.QuickTest.<clinit>(QuickTest.java:32)
private static final Logger logger = LogManager.getLogger("QuickTest");
#ObjectFactory
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
#Test
public void socketTest() throws IOException {
int bytesWritten = 5;
SocketChannel socketChannel = PowerMockito.mock(SocketChannel.class);
SocketAddress socketAddress = new InetSocketAddress("abc.com", 12340);
Mockito.when(socketChannel.getRemoteAddress()).thenReturn(socketAddress);
Mockito.when(socketChannel.write((ByteBuffer) Mockito.any())).thenReturn(bytesWritten);
// todo: socketChannel.register() is causing Mockito to throw null pointer exception because it's a final method
Mockito.doNothing().when(socketChannel.register(Mockito.any(), Mockito.any()));
// further stuff down here to setup and do test
}
}
First problem
It is having a problem with the following line.
private static final Logger logger = LogManager.getLogger("QuickTest");
This is the full stack trace.
org.testng.TestNGException:
An error occurred while instantiating class com.QuickTest: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:385)
at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:285)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:126)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:191)
at org.testng.TestClass.getInstances(TestClass.java:104)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:90)
at org.testng.TestClass.init(TestClass.java:82)
at org.testng.TestClass.<init>(TestClass.java:45)
at org.testng.TestRunner.initMethods(TestRunner.java:422)
at org.testng.TestRunner.init(TestRunner.java:252)
at org.testng.TestRunner.init(TestRunner.java:222)
at org.testng.TestRunner.<init>(TestRunner.java:163)
at org.testng.SuiteRunner$DefaultTestRunnerFactory.newTestRunner(SuiteRunner.java:566)
at org.testng.SuiteRunner.init(SuiteRunner.java:170)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:117)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1359)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1346)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1200)
at org.testng.TestNG.runSuites(TestNG.java:1124)
at org.testng.TestNG.run(TestNG.java:1096)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:71)
at org.apache.logging.log4j.LogManager.<clinit>(LogManager.java:60)
at com.QuickTest.<clinit>(QuickTest.java:32)
at sun.misc.Unsafe.ensureClassInitialized(Native Method)
at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(UnsafeFieldAccessorFactory.java:43)
at sun.reflect.ReflectionFactory.newFieldAccessor(ReflectionFactory.java:156)
at java.lang.reflect.Field.acquireFieldAccessor(Field.java:1088)
at java.lang.reflect.Field.getFieldAccessor(Field.java:1069)
at java.lang.reflect.Field.set(Field.java:764)
at javassist.util.proxy.ProxyFactory.setField(ProxyFactory.java:526)
at javassist.util.proxy.ProxyFactory.createClass3(ProxyFactory.java:509)
at javassist.util.proxy.ProxyFactory.createClass2(ProxyFactory.java:493)
at javassist.util.proxy.ProxyFactory.createClass1(ProxyFactory.java:429)
at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:400)
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.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1846)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:810)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:675)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.modules.testng.internal.TestClassInstanceFactory.createProxyTestClass(TestClassInstanceFactory.java:91)
at org.powermock.modules.testng.internal.TestClassInstanceFactory.createTestClass(TestClassInstanceFactory.java:78)
at org.powermock.modules.testng.internal.TestClassInstanceFactory.create(TestClassInstanceFactory.java:49)
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:373)
... 21 more
Second problem
If I comment out the logger I am getting the following.
org.testng.TestNGException:
An error occurred while instantiating class com.QuickTest: Cannot create a new instance of test class class com.QuickTest
at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:385)
at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:285)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:126)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:191)
at org.testng.TestClass.getInstances(TestClass.java:104)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:90)
at org.testng.TestClass.init(TestClass.java:82)
at org.testng.TestClass.<init>(TestClass.java:45)
at org.testng.TestRunner.initMethods(TestRunner.java:422)
at org.testng.TestRunner.init(TestRunner.java:252)
at org.testng.TestRunner.init(TestRunner.java:222)
at org.testng.TestRunner.<init>(TestRunner.java:163)
at org.testng.SuiteRunner$DefaultTestRunnerFactory.newTestRunner(SuiteRunner.java:566)
at org.testng.SuiteRunner.init(SuiteRunner.java:170)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:117)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1359)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1346)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1200)
at org.testng.TestNG.runSuites(TestNG.java:1124)
at org.testng.TestNG.run(TestNG.java:1096)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.RuntimeException: Cannot create a new instance of test class class com.QuickTest
at org.powermock.modules.testng.internal.TestClassInstanceFactory.create(TestClassInstanceFactory.java:59)
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:373)
... 21 more
Caused by: java.lang.reflect.InvocationTargetException
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)
... 24 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:71)
at org.apache.logging.log4j.LogManager.<clinit>(LogManager.java:60)
at org.apache.commons.logging.LogFactory$Log4jLog.<clinit>(LogFactory.java:199)
at org.apache.commons.logging.LogFactory$Log4jDelegate.createLog(LogFactory.java:166)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:109)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:99)
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.<init>(AbstractTestNGSpringContextTests.java:92)
at com.QuickTest.<init>(QuickTest.java:26)
at com.QuickTest_$$_jvst738_0.<init>(QuickTest_$$_jvst738_0.java)
... 29 more
Third problem
If I remove the 'extends AbstractTestNGSpringContextTests' bit on the class I am still getting the following. At this point I'm not sure what else I can try.
java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)
at org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:74)
at com.sun.proxy.$Proxy13.getHandler(Unknown Source)
at org.mockito.internal.util.MockUtil.isMock(MockUtil.java:81)
at org.mockito.internal.configuration.injection.scanner.MockScanner.isMockOrSpy(MockScanner.java:83)
at org.mockito.internal.configuration.injection.scanner.MockScanner.preparedMock(MockScanner.java:71)
at org.mockito.internal.configuration.injection.scanner.MockScanner.scan(MockScanner.java:59)
at org.mockito.internal.configuration.injection.scanner.MockScanner.addPreparedMocks(MockScanner.java:45)
at org.mockito.internal.configuration.InjectingAnnotationEngine.injectMocks(InjectingAnnotationEngine.java:82)
at org.powermock.api.mockito.internal.configuration.PowerMockitoInjectingAnnotationEngine.process(PowerMockitoInjectingAnnotationEngine.java:36)
at org.powermock.api.extension.listener.AnnotationEnabler.injectSpiesAndInjectToSetters(AnnotationEnabler.java:61)
at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:56)
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.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1846)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:700)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:415)
at org.powermock.modules.testng.internal.PowerMockTestNGMethodHandler.injectMocksUsingAnnotationEnabler(PowerMockTestNGMethodHandler.java:76)
at org.powermock.modules.testng.internal.PowerMockTestNGMethodHandler.invoke(PowerMockTestNGMethodHandler.java:48)
at com.QuickTest_$$_jvst2c0_0.setup(QuickTest_$$_jvst2c0_0.java)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1284)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1209)
at org.testng.TestNG.runSuites(TestNG.java:1124)
at org.testng.TestNG.run(TestNG.java:1096)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.IllegalStateException: Failed to load interface org.mockito.plugins.MockMaker implementation declared in sun.misc.CompoundEnumeration#6302bbb1
at org.mockito.internal.configuration.plugins.PluginInitializer.loadImpl(PluginInitializer.java:54)
at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:57)
at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:44)
at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:21)
at org.mockito.internal.configuration.plugins.Plugins.<clinit>(Plugins.java:18)
at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:24)
... 44 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.PluginInitializer.loadImpl(PluginInitializer.java:50)
... 49 more
Related
I am not able do proper mock one of the AWS translation client due to expending nested abstract class:
Java class
import com.amazonaws.services.comprehend.AmazonComprehend;
import com.amazonaws.services.translate.AmazonTranslate;
public class TestLambdaFunctionHandler implements RequestHandler<InputPayLoadPojo, Response> {
AmazonTranslate awsTranslateClient = null;
AmazonComprehend comprehendClient = null;
awsTranslateClient = AmazonTranslateClientBuilder.standard().build();
comprehendClient = AmazonComprehendClientBuilder.standard().build();
........
}
Junit test class
import com.amazonaws.services.comprehend.AmazonComprehend;
import com.amazonaws.services.translate.AmazonTranslate;
import com.amazonaws.services.comprehend.AmazonComprehendClientBuilder;
import com.amazonaws.services.translate.AmazonTranslateClientBuilder;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;
import junit.framework.TestCase;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static com.google.common.util.concurrent.Runnables.doNothing;
import static org.powermock.api.mockito.PowerMockito.whenNew;
#RunWith(PowerMockRunner.class)
#PowerMockIgnore({ "javax.net.ssl.*" })
#PrepareForTest({AmazonComprehendClientBuilder.class, AmazonComprehendClientBuilder , AmazonTranslate.class, AmazonComprehend.class,})
public class SynchronousTest {
#Before
public void setup() {
}
#Test
public void testSynchronousTranslation() {
TaaSSyncLambdaFunctionHandler obj = Mockito.spy(new TaaSSyncLambdaFunctionHandler());
AmazonTranslate awsTransMock = PowerMockito.mock(AmazonTranslate.class);
AmazonComprehend awsComprehendMock = PowerMockito.mock(AmazonComprehend.class);
AmazonTranslateClientBuilder awsTranslateClientBuilderMock = PowerMockito.mock(AmazonTranslateClientBuilder.class);
AmazonComprehendClientBuilder awsComprehendClientBuilderMock = PowerMockito.mock(AmazonComprehendClientBuilder.class);
when(awsTranslateClientBuilderMock.standard().build()).thenReturn(awsTransMock);
when(awsComprehendClientBuilderMock.standard().build()).thenReturn(awsComprehendMock);
...................
}
}
error:
com.amazonaws.SdkClientException: Unable to find a region via the region provider chain. Must provide an explicit region in the builder or setup environment to supply a region.
at com.amazonaws.client.builder.AwsClientBuilder.setRegion(AwsClientBuilder.java:386)
at com.amazonaws.client.builder.AwsClientBuilder.configureMutableProperties(AwsClientBuilder.java:352)
at com.amazonaws.client.builder.AwsSyncClientBuilder.build(AwsSyncClientBuilder.java:46)
at taas.amazonservices.lambda.SynchronousTest.testSynchronousTranslation(SynchronousTest.java:89)
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.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
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:298)
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:218)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
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:136)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
After investigation found that AmazonTranslateClientBuilder extends abstract classs AwsSyncClientBuilder
and AwsSyncClientBuilder extends abstract class.
This is found below.
public final class AmazonTranslateClientBuilder extends AwsSyncClientBuilder<AmazonTranslateClientBuilder, AmazonTranslate> {
public abstract class AwsSyncClientBuilder<Subclass extends AwsSyncClientBuilder, TypeToBuild> extends AwsClientBuilder<Subclass, TypeToBuild> {
even after adding below mock for abstract class, still getting same error:
AwsSyncClientBuilder cut= Mockito.mock(AwsSyncClientBuilder.class,Mockito.CALLS_REAL_METHODS);
AwsClientBuilder cut1= Mockito.mock(AwsClientBuilder.class,Mockito.CALLS_REAL_METHODS);
Please provide any technical to resove these type of class.
Thanks,
Ranjit Kumar
I am trying to set up my unit tests so that I can test my HBase Client. However, I am having trouble mocking the creation of the connection to HBase in the constructor. I don't think I am correctly injecting the mocked connection into the class I want to test, but I'm not sure where I made the mistake. I've looked at similar questions about mocking a connection, but all of those have the creation of the connection outside of the constructor.
This is the code I am trying to test:
#Lazy
#Service("HBaseClient")
public class HBaseClient {
/**
* Instantiate a new client and create connection to HBase.
*/
public HBaseClient() {
// Create connection to HBase
conf = HBaseConfiguration.create();
conf.setInt("timeout", 120000);
conf.set("hbase.zookeeper.quorum", zookeeperHost);
conf.set("hbase.zookeeper.property.clientPort", zookeeperPort);
conf.set("zookeeper.znode.parent", znodeParent);
try {
connection = ConnectionFactory.createConnection(conf);
} catch (IOException e) {
logger.error("Error creating connection to HBase - IOException");
}
}
public void addRecord(String rowKey, String columnFamily, Map<String, String> values) {
...
Here is what I have in the unit test:
#RunWith(PowerMockRunner.class)
public class TestHBaseClient {
#InjectMocks
private static HBaseClient hbaseClient;
#BeforeClass
#PrepareForTest({ConnectionFactory.class})
public static void setUpBeforeClass() throws Exception {
Connection mockConnection = PowerMockito.mock(Connection.class);
PowerMockito.mockStatic(ConnectionFactory.class);
PowerMockito.when(ConnectionFactory.createConnection()).thenReturn(mockConnection);
hbaseClient = new HBaseClient();
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
}
#Test
public void testAddRecord() {
HashMap<String, String> values = new HashMap<String, String>();
values.put("test1", "abc");
values.put("test2", "xyz");
hbaseClient.addRecord("test", "Test", values);
}
}
The code as it currently is throws the following error:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public. It is a limitation of the mock engine.
at org.powermock.api.mockito.PowerMockito.when(PowerMockito.java:495)
at
com.rtn.cdp.storage.hbase.test.TestHBaseDataClient.setUpBeforeClass(TestHBaseClient.java:32)
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.internal.runners.ClassRoadie.runBefores(ClassRoadie.java:56)
at
org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:43)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:101)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at
org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
I am just tryig to understand the Soap WS. So I just write some simple classes as follow. but when I deploy this application in GlassFish and test it, the server returns the java.lang.reflect.InvocationTargetException. Can anybody say what the problem is?
#WebService
public class AuthorWS {
AuthorService authorService = new AuthorService();
#WebMethod
public Author getAuthorById(int authorId) {
return authorService.getAuthorById(authorId);
}
#WebMethod
public ArrayList<Author> getAllAuthors() {
return authorService.getAllAuthors();
}
}
Service Class:
public class AuthorService {
AuthorDAO authorDAO = new AuthorDAO();
public Author getAuthorById(int authorId){
return authorDAO.getAuthorById(authorId);
}
public ArrayList<Author> getAllAuthors(){
return authorDAO.getAllAuthors();
}
}
DAO Class:
public class AuthorDAO {
public Author getAuthorById(int authorId){
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Criteria criteria = sessionFactory.openSession().createCriteria(Author.class);
criteria.add(Restrictions.eq("authorId", authorId));
return (Author) criteria.uniqueResult();
}
public ArrayList<Author> getAllAuthors(){
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Criteria criteria = sessionFactory.openSession().createCriteria(Author.class);
return (ArrayList<Author>) criteria.list();
}
Exception:
'Caused by: java.lang.reflect.InvocationTargetException 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:483) at org.glassfish.webservices.monitoring.WebServiceTesterServlet.doPost(WebServiceTesterServlet.java:313) ... 32 more Caused by: com.sun.xml.ws.fault.ServerSOAPFaultException: Client received SOAP Fault from server: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class com.hojat.LibrarySoapWS.ws.AuthorWS Please see the server log to find more detail regarding exact cause of the failure. at com.sun.xml.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:193) at com.sun.xml.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:131) at com.sun.xml.ws.client.sei.StubHandler.readResponse(StubHandler.java:253) at com.sun.xml.ws.db.DatabindingImpl.deserializeResponse(DatabindingImpl.java:203) at com.sun.xml.ws.db.DatabindingImpl.deserializeResponse(DatabindingImpl.java:290) at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119) at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:92) at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:161) at com.sun.proxy.$Proxy312.getAllAuthors(Unknown Source)'
The problem is on the server side, as you can see from the stack trace
: Client received SOAP Fault from server:
com.sun.enterprise.container.common.spi.util.InjectionException:
Error creating managed object for class:
class com.hojat.LibrarySoapWS.ws.AuthorWS
Please see the server log to find more detail regarding exact cause of the failure.
So check the server log.
Hi I am new to Web Services, I have the requirement of Code First Approach,
I have an interface like below
package in.co.way2learn;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
#WebService(name="SQS",portName="SQSP",serviceName="SQSS")
public interface StockQuoteService {
#WebMethod(operationName="getPrice")
public double getPrice(#WebParam(name="symbol")String symbol);
#WebMethod(operationName="aaa",action="aaaAction")
public boolean update(#WebParam(name="sybmol")String symbol,#WebParam(name="price")double price);
#WebMethod(operationName="bbb",action="bbbAction")
public boolean update(#WebParam(name="sybmol")String symbol,#WebParam(name="price")double price,#WebParam(name="flag")boolean flag);
}
I want to expose an implementation if the the above interface as web service.
The implementation class is as below:
package in.co.way2learn;
import javax.jws.WebMethod;
import javax.jws.WebService;
#WebService(name="SQSI",
endpointInterface="in.co.way2learn.StockQuoteService",
portName="SQSIP",serviceName="SQSIS")
public class StockQuoteServiceImpl implements StockQuoteService{
#Override
public double getPrice(String symbol) {
System.out.println("StockQuoteServiceImpl.getPrice()");
return 123;
}
#Override
#WebMethod(operationName="aaa",action="aaaAction")
public boolean update(String symbol, double price) {
System.out.println("StockQuoteServiceImpl.update()");
return true;
}
#Override
#WebMethod(operationName="bbb",action="bbbAction")
public boolean update(String symbol, double price, boolean flag) {
System.out.println("StockQuoteServiceImpl.update()");
return true;
}
}
To expose this service as web service I am using JDK's EndPoint class as below.
package in.co.way2learn;
import javax.xml.ws.Endpoint;
public class Server {
public static void main(String[] args) {
StockQuoteService stockQuoteService=new StockQuoteServiceImpl();
String address="http://localhost:8080/sqs";
Endpoint.publish(address, stockQuoteService);
System.out.println("Server started..!");
}
}
But When I run the server program I am getting the following exception.
Exception in thread "main" javax.xml.ws.WebServiceException: class in.co.way2learn.jaxws.Update do not have a property of the name flag
at com.sun.xml.internal.ws.server.sei.EndpointArgumentsBuilder$DocLit.<init>(Unknown Source)
at com.sun.xml.internal.ws.server.sei.EndpointMethodHandler.createArgumentsBuilder(Unknown Source)
at com.sun.xml.internal.ws.server.sei.EndpointMethodHandler.<init>(Unknown Source)
at com.sun.xml.internal.ws.server.sei.SEIInvokerTube.<init>(Unknown Source)
at com.sun.xml.internal.ws.server.EndpointFactory.createEndpoint(Unknown Source)
at com.sun.xml.internal.ws.api.server.WSEndpoint.create(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.createEndpoint(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(Unknown Source)
at javax.xml.ws.Endpoint.publish(Unknown Source)
at in.co.way2learn.Server.main(Server.java:10)
Caused by: javax.xml.bind.JAXBException: flag is not a valid property on class in.co.way2learn.jaxws.Update
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getElementPropertyAccessor(Unknown Source)
... 11 more
Here in StockQuoteService interface and corresponding implementation I have two overloaded update method one is taking two parameters while other is taking three.
If I change second update method name to different name, then the server is running fine without exception.
But exception is coming when i have overloaded update methods only.
Even though I kept overloaded methods, their operation names and corresponding soap actions are different, you can see them in annotations on top of the methods.
Any help will give me great relief and appreciated as well.
I have the following situation:
Using RMI, i noticed that under a specific situation, the RMI client did not have the class whose instance was sent via RMI. So, I sent the class in the shape of Byte [] and then loaded it with a class loader i defined.
The code in the client side is something like:
pp = plugins.getPanelClasses(); //RMI method
panelClassLoader pcl = new panelClassLoader(); //simple class loader defined by me
String name = pcl.defineClass(pp);
Then, i ask in the client side by the instance of the class loaded:
HashMap<String, PluginPanel> panels = null;
try
{
panels = plugins.getSettingsPanels();
} catch (RemoteException ex)
{
Logger.getLogger(ServerOptions.class.getName()).log(Level.SEVERE, null, ex);
}
PluginPanel is an interface whose implementing classes are not always in the client...
and the class loader is:
private class panelClassLoader extends ClassLoader
{
public panelClassLoader(ClassLoader parent)
{
super(parent);
}
public panelClassLoader()
{
super(getSystemClassLoader());
}
public String defineClass(byte[] b)
{
Class c = super.defineClass(null, b, 0, b.length);
resolveClass(c);
return c.getName();
}
}
Nevertheless, I'm stuck with the following error:
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: pt.ua.dicoogle.IndexPlugin.CPanel (no security manager: RMI class loader disabled)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:178)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:178)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:132)
at $Proxy22.getSettingsPanels(Unknown Source)
at pt.ua.dicoogle.rGUI.client.windows.ServerOptions.(ServerOptions.java:176)
Caused by: java.lang.ClassNotFoundException: pt.ua.dicoogle.IndexPlugin.CPanel (no security manager: RMI class loader disabled)
at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:375)
at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:165)
at java.rmi.server.RMIClassLoader$2.loadClass(RMIClassLoader.java:620)
at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247)
at sun.rmi.server.MarshalInputStream.resolveClass(MarshalInputStream.java:197)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1574)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1495)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1731)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
at java.util.HashMap.readObject(HashMap.java:1030)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1848)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:306)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:155)
Any sugestion?
You would have to call the remote method in the context of that class loader. Not a good scheme. Have a good look at the RMI codebase feature, it is designed for exactly this situation.