Casting Error related to XmlBeanFactory - java

When trying to run the Junit Test I got this error. This line :
AppConfig.getGatewayConfigurations().getURL();
is working fine on some places. Also I have no problem related to the path of XML File. And the class GatewayConfigurations is built well and its attributes assigned well in bean configuration file !
Here is the trace
java.lang.ClassCastException: org.springframework.beans.factory.xml.XmlBeanFactory cannot be cast to com.me.vpc.configurations.GatewayConfigurations
at com.me.vpc.configurations.AppConfig.getGatewayConfigurations(AppConfig.java:26)
at com.me.vpc.test.PaymentQueryStringBuilderThirdPartyTest.buildQueryStringTest(PaymentQueryStringBuilderThirdPartyTest.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMethod(JUnit4ClassRunner.java:88)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
PaymentQueryStringBuilderThirdPartyTest Class
package com.me.vpc.test;
import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.me.vpc.common.PaymentQueryStringBuilderThirdParty;
import com.me.vpc.configurations.AppConfig;
public class PaymentQueryStringBuilderThirdPartyTest {
#SuppressWarnings("rawtypes")
private Map parameters;
#SuppressWarnings({ "unchecked", "rawtypes" })
#Before
public void setUp() throws Exception {
parameters = new HashMap();
parameters.put("vpc_Merchant", "MER123");
parameters.put("vpc_OrderInfo", "A48cvE28");
parameters.put("vpc_Amount", "2995");
}
#Test
public void buildQueryStringTest() throws UnsupportedEncodingException {
String URL = AppConfig.getGatewayConfigurations().getURL();
String expectedQueryString = URL + "?vpc_Merchant=MER123&vpc_OrderInfo=A48cvE28&vpc_Amount=2995";
assertEquals(expectedQueryString, PaymentQueryStringBuilderThirdParty.buildQueryString(parameters));
}
}
AppConfig Class
public class AppConfig {
/**
* Default xml configurations file
*/
private final static String APP_CONFIG_FILE = "vpc-configurations.xml";
/**
* Load gateway configurations
* #return GatwayConfigurations object
*/
public static GatewayConfigurations getGatewayConfigurations(){
return (GatewayConfigurations)getBeans();
}
/**
* Get the desired configuration bean
* #param beanName
* #return BeanFactory object
*/
private static BeanFactory getBeans()
{
return new XmlBeanFactory(new FileSystemResource(APP_CONFIG_FILE));
}
}

Looking at the API for XmlBeanFactory, I can't see how it could be cast to com.me.vpc.configurations.GatewayConfigurations (not surprisingly because you have created that class / interface).
getBeans() returns a XmlBeanFactory, and getGatewayConfigurations() casts that to GatewayConfigurations. This will never work.

Related

MockMVC Test reports does not declare any static, non-private, non-final, inner classes annotated with #Configuration

I am trying to call my ajax method via a Junit test case. I have referred to a truck load of SO questions to get to this point. But still I am getting
TestMockMVC does not declare any static, non-private, non-fin
al, inner classes annotated with #Configuration.
My AJAX call is
#RequestMapping(value = { "/saveEntityAjax", "/modifyEntityAjax" }, method = RequestMethod.POST)
public #ResponseBody String saveOrUpdateEntityAjax(
#RequestParam(value = "id") String id,
#RequestParam(value = "number") String number, HttpServletRequest httpServletRequest) {
My Junit Test case is
package test.controllers;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.mnox.database.pojo.wrapper.v2.VehicleMasterPojoWrapper.VehiclePurpose;
#Configuration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader=AnnotationConfigWebContextLoader.class)
#WebAppConfiguration
public class TestMockMVC {
#Autowired
private WebApplicationContext context;
private MockMvc mvc;
#Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
#Test
public void test1CreateClient() {
SaveOrUpdateVehicleAjaxRequest vehicle = new SaveOrUpdateVehicleAjaxRequest("123", "KA-02-1234", 12,
VehiclePurpose.MAIN_VEHICLE.name(), "some alias");
try {
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post("/saveVehicleAjaxMethod")
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andReturn();
mvcResult.getModelAndView();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class SaveOrUpdateEntityAjaxRequest {
private String id;
private String number;
public SaveOrUpdateEntityAjaxRequest(String id, String number) {
super();
this.id = id;
this.number = number;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
}
I am getting the following errors
INFO : org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [test.controllers.TestMockMVC]: TestMockMVC does not declare any static, non-private, non-final, inner classes annotated with #Configuration.
INFO : org.springframework.test.context.web.WebTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
INFO : org.springframework.test.context.web.WebTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#7f3b84b8, org.springframework.test.context.support.DependencyInjectionTestExecutionListener#57a3af25, org.springframework.test.context.support.DirtiesContextTestExecutionListener#2b662a77, org.springframework.test.context.transaction.TransactionalTestExecutionListener#7f0eb4b4, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#5c33f1a9, org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener#1623b78d, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#c8c12ac, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#6adbc9d]
INFO : org.springframework.web.context.support.GenericWebApplicationContext - Refreshing org.springframework.web.context.support.GenericWebApplicationContext#3eb25e1a: startup date [Mon Sep 11 13:11:05 IST 2017]; root of context hierarchy
INFO : org.springframework.web.context.support.GenericWebApplicationContext - Closing org.springframework.web.context.support.GenericWebApplicationContext#3eb25e1a: startup date [Mon Sep 11 13:11:05 IST 2017]; root of context hierarchy
Edit : Jar's I am using are
spring-boot-test-1.4.0.RELEASE.jar
spring-security-test-4.0.0.RELEASE.jar
spring-context-3.1.0.RELEASE.jar
spring-test-4.1.9.RELEASE.jar
spring-core-3.1.0.RELEASE.jar
spring-web-3.1.0.RELEASE.jar
spring-expression-3.1.0.RELEASE.jar
spring-webmvc-3.1.0.RELEASE.jar
Edit : My folder structure is
src/main/java/test/controllers/TestMockMVC.java
src/main/webapp/WEB-INF/web.xml
src/main/webapp/WEB-INF/spring/root-context.xml
src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml
Edit :
I have a partial answer. I have modified my code to solve the issue reported in this question. Although I am stuck at a different point, I am answering the question partially.
CHANGE 1
#Configuration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({
// "file:src/main/webapp/WEB-INF/web.xml"
"file:src/main/webapp/WEB-INF/spring/root-context.xml",
"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" })
#WebAppConfiguration
public class TestMockMVC {
#Autowired
FilterChainProxy springSecurityFilterChain;
#Autowired
private WebApplicationContext context;
private MockMvc mvc;
#Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain)).build();
}
#Test
public void test1CreateClient() {
SaveOrUpdateEntityAjaxRequest vehicle = new SaveOrUpdateEntityAjaxRequest("123", "KA-02-1234");
MvcResult mvcResult = null;
try {
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post("/saveEntityAjaxMethod")
.content(new Gson().toJson(vehicle).getBytes()).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
mvcResult = mvc.perform(request).andReturn();
mvcResult.getModelAndView();
} catch (Exception e) {
e.printStackTrace();
}
}
CHANGE 2
In my servlet-context.xml I added the following lines.
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<!-- properties -->
</bean>
Exception I am getting now
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 67 ms
java.lang.NullPointerException
at org.springframework.security.web.FilterChainProxy.getFilters(FilterChainProxy.java:223)
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.springframework.util.MethodInvoker.invoke(MethodInvoker.java:269)
at org.springframework.test.util.ReflectionTestUtils.invokeMethod(ReflectionTestUtils.java:307)
at org.springframework.security.test.web.support.WebTestUtils.findFilter(WebTestUtils.java:118)
at org.springframework.security.test.web.support.WebTestUtils.getSecurityContextRepository(WebTestUtils.java:57)
at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$SecurityContextRequestPostProcessorSupport.save(SecurityMockMvcRequestPostProcessors.java:434)
at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$TestSecurityContextHolderPostProcessor.postProcessRequest(SecurityMockMvcRequestPostProcessors.java:511)
at org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.postProcessRequest(MockHttpServletRequestBuilder.java:686)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:137)
at test.controllers.TestMockMVC.test1CreateClient(TestMockMVC.java:61)
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.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:70)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
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:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

PowerMockito (with Mockito) failing with ExceptionInInitializerError

We are using Powermockito with Mockito to mock some static classes. There seems to be java.lang.ExceptionInInitializerError thrown every time.
Can you help me identify where the problem is?
Java class under test
package com.myproject.myproduct.search.domain;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
public class MyQueryBuilder {
public MultiMatchQueryBuilder getMultiMatchQueryBuilder() {
MultiMatchQueryBuilder builder = QueryBuilders.multiMatchQuery("term", "field1");
builder.field("field1",200.9f);
return builder;
}
}
Junit test with Powermock runner
package com.myproject.myproduct.search.domain;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(QueryBuilders.class)
public class MyQueryBuilderTest {
private MyQueryBuilder myQueryBuilder;
#Test
public void test() {
PowerMockito.mockStatic(QueryBuilders.class);
MultiMatchQueryBuilder builder = PowerMockito.mock(MultiMatchQueryBuilder.class);
}
}
That's it. The test code does not work as soon as I try to mock
MultiMatchQueryBuilder.
This is the Exception:
java.lang.ExceptionInInitializerError at
org.elasticsearch.common.logging.DeprecationLogger.(DeprecationLogger.java:138)
at org.elasticsearch.common.ParseField.(ParseField.java:35)
at
org.elasticsearch.index.query.AbstractQueryBuilder.(AbstractQueryBuilder.java:53)
at
sun.reflect.GeneratedSerializationConstructorAccessor7.newInstance(Unknown
Source) at
java.lang.reflect.Constructor.newInstance(Constructor.java:423) at
org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:40)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:59) at
org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:128)
at
org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:63)
at
org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:111)
at
org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:60)
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:143)
at
com.spartasystems.stratas.search.domain.MyQueryBuilderTest.testBoostSetProperly(MyQueryBuilderTest.java:22)
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:310)
at
org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:88)
at
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
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:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
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:33)
at
org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
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.junit.runner.JUnitCore.run(JUnitCore.java:160) 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: java.lang.NullPointerException at
org.elasticsearch.Build.(Build.java:47) ... 41 more
Process finished with exit code 255
Note:
The source code of actual underlying elasticsearch classes can be found here
https://github.com/elastic/elasticsearch/blob/master/core/src/main/java/org/elasticsearch/index/query/QueryBuilders.java
and
https://github.com/elastic/elasticsearch/blob/master/core/src/main/java/org/elasticsearch/index/query/MultiMatchQueryBuilder.java
When calling with mocks org.elasticsearch.Build#getElasticsearchCodebase
Build.class.getProtectionDomain().getCodeSource().getLocation()
returns null because the code has no location (Dynamic method generated by cglib.)
So when initializing org.elasticsearch.Build during your mock code using
final URL url = getElasticsearchCodebase(); // url is null
final String urlStr = url.toString(); // null pointer exception.
Of course, the mock will not success and throw ExceptionInInitializerError which indicates an exception occurred during evaluation of a static initializer or the initializer for a static variable.
You can easily reproduce this exception using following code:
#RunWith(PowerMockRunner.class)
#PrepareForTest({QueryBuilders.class})
public class MyQueryBuilderTest {
#Test
public void test() {
final Build current = Build.CURRENT;
}
}

SSLContext mock not behaving as expected

I've the following simple class:
import javax.net.ssl.SSLContext;
public class AClass {
public void someMethod() throws Exception {
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, null, null);
}
}
And its JUnit:
import javax.net.ssl.SSLContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest({ SSLContext.class })
public class ATest {
#Test
public void testSomeMethod() throws Exception {
PowerMockito.mockStatic(SSLContext.class);
SSLContext context = Mockito.mock(SSLContext.class);
Mockito.when(context.getInstance("SSL")).thenReturn(context);
new AClass().someMethod();
}
}
The JUnit fails with the following stack trace:
java.lang.NullPointerException
at javax.net.ssl.SSLContext.init(Unknown Source)
at random.AClass.someMethod(AClass.java:8)
at random.ATest.testSomeMethod(ATest.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:316)
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:300)
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:288)
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:208)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:121)
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:123)
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:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
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)
The stack trace points to the line with context.init(null, null, null); having a null pointer. However when I debug (in Eclipse), I can clearly see that the value of the context variable is a Mock for SSLContext, hashCode: 1857173583. If a mock, then a void method like init() shouldn't do anything. So, why is it throwing a NullPointerException?
Looking at the API and decompiled signature for the init method which throws the NPE, it shows as final, which basic Mockito.mock() can not handle.
On the other hand, the javadoc for PowerMockito.mock() reads:
org.powermock.api.mockito.PowerMockito
public static T mock(Class type)
Creates a mock object that supports mocking of final and native methods.
Type Parameters:
    T - the type of the mock object
Parameters:
    type - the type of the mock object
Returns:
    the mock object.
So, changing a bit your test should make it work:
#RunWith(PowerMockRunner.class)
#PrepareForTest({SSLContext.class})
public class ATest {
#Test
public void testSomeMethod() throws Exception {
// create the mock to return by getInstance()
SSLContext context = PowerMockito.mock(SSLContext.class);
// mock the static method getInstance() to return above created mock context
PowerMockito.mockStatic(SSLContext.class);
Mockito.when(SSLContext.getInstance("SSL")).thenReturn(context);
// invoke the object under test
new AClass().someMethod();
//TODO - add verifications / assertions
}
}
Update:
Since you're running the test with the PowerMockRunner, you can also replace
SSLContext context = PowerMockito.mock(SSLContext.class);
with a field
#Mock
private SSLContext context;
which will also be handled by PowerMock (or use MockitoJUnitRunner if you just need basic mockito)

Spring controller unit testing with spring-test-mvc is failing

I am learning unit testing of spring controller with EasyMock and Spring test framework. I have done a simple unit testing for my controller.
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.firstmav.domain.Employee;
import com.firstmav.service.EmployeeService;
#Controller
public class DataController {
#Autowired
EmployeeService employeeservice;
#RequestMapping("form")
public ModelAndView getform(#ModelAttribute Employee employee){
return new ModelAndView("form");
}
#RequestMapping("reguser")
public ModelAndView registeruser(#ModelAttribute Employee employee){
employeeservice.insertRow(employee);
return new ModelAndView("redirect:list");
}
#RequestMapping("list")
public ModelAndView getlist(){
List<Employee> employeelist = employeeservice.getList();
return new ModelAndView("list", "employeeList", employeelist);
}
#RequestMapping("delete")
public ModelAndView deleteitem(#RequestParam int id){
employeeservice.deleteRow(id);
return new ModelAndView("redirect:list");
}
#RequestMapping("edit")
public ModelAndView edititem(#ModelAttribute Employee employee, #RequestParam int id){
Employee employeeObject = employeeservice.getRowByID(id);
return new ModelAndView("edit", "employeeObject", employeeObject);
}
#RequestMapping("update")
public ModelAndView updaterow(#ModelAttribute Employee employee){
employeeservice.updateRow(employee);
return new ModelAndView("redirect:list");
}
}
and i have my failing test case here.
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.firstmav.controller.DataController;
public class DataControllerTest {
private MockMvc mockmvc;
#Before
public void setup(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
mockmvc = MockMvcBuilders.standaloneSetup(new DataController()).setViewResolvers(viewResolver).build();
}
#Test
public void main() throws Exception{
mockmvc.perform(get("/form")).andExpect(status().isOk()).andExpect(view().name("form"));
}
}
I have included the controller import in the test case but i always getting the noclassdeffound exception.
java.lang.NoClassDefFoundError: javax/servlet/ServletException
at org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup(MockMvcBuilders.java:71)
at com.ada.test.DataControllerTest.setup(DataControllerTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 25 more
I don't understand where i am making the mistake. Can any one help me or point me to right direction?
The issue is not related with your code.You're missing the library(jar) which contains javax.servlet.ServletException.So at runtime you're getting this exception.Check you class path if you have the servlet-api.jar in that location.
Though adding servlet-api.jar into your class path location should resolve the issue but if you want you can also check the jars that have this class here

Using Singleton Class in spring mvc to get data

I create a singleton class and calling a method inside it. I use spring mvc SimpleJdbcTemplate for retrieving data from database, but I get NullPointerException. Code I wrote is:
package in.dewsolutions.jc.utils;
import in.dewsolutions.jc.dao.ReportsDAO;
import in.dewsolutions.jc.dto.ReportsView;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
public class SingletonFilterData {
private static final Logger logger = Logger.getLogger(SingletonFilterData.class);
#Autowired
private SimpleJdbcTemplate simpleJdbcTemplate;
#Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
private SingletonFilterData() // private defaul constructor
{
}
private static SingletonFilterData reference = null;
public static SingletonFilterData getInstance() {
if (reference == null) {
synchronized (SingletonFilterData.class) {
if (reference == null) {
reference = new SingletonFilterData();
}
}
}
return reference;
}
public List<ReportsView> findManuFacturer() {
// TODO Auto-generated method stub
List<ReportsView> manufacturer = new ArrayList<ReportsView>();
ReportsView rv = new ReportsView();
rv.setProductName("None");
rv.setProductId(0);
manufacturer.add(rv);
String query = "SELECT * FROM manufacturer ORDER BY name";
ParameterizedRowMapper<ReportsView> mapper = new ParameterizedRowMapper<ReportsView>() {
public ReportsView mapRow(ResultSet rs, int rowNum)
throws SQLException {
ReportsView reportsView = new ReportsView();
reportsView.setProductName(rs.getString("name"));
reportsView.setProductId(rs.getLong("id_manufacturer"));
return reportsView;
}
};
manufacturer.addAll(simpleJdbcTemplate.query(query, mapper));
return manufacturer;
}
The exception I get is:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
root cause
java.lang.NullPointerException
in.dewsolutions.jc.utils.SingletonFilterData.findManuFacturer(SingletonFilterData.java:77)
in.dewsolutions.jc.controller.ReportsController.filterQuantity(ReportsController.java:169)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.29 logs.
How can I remove the Exception?
Using new SingletonFilterData() doesn't invoke the autowiring, so simpleJdbcTemplate remains null.
Instead of implementing getInstance(), you can configure Spring so that SingletonFilterData is a singleton and injected into ReportsController.

Categories

Resources