How to test Servlet on Mockito? - java

I'm new to mokito, I'm trying to test my servlet who is responsible for registering the user. I'm trying to lock up the HttpRequestServlet but I always get ClassFormException. I can not understand why. How can this be fixed, can you tell? How it is possible to properly test a servlet and to mock HttpServletRequest?
#Mock
private HttpServletRequest request = mock(HttpServletRequest.class); ;
#After
public void verifyRequest(){
verify(request).getParameter(ConstantApp.RegistrationConstantField.GET_FIRST_NAME);
verify(request).getParameter(ConstantApp.RegistrationConstantField.GET_LAST_NAME);
verify(request).getParameter(ConstantApp.RegistrationConstantField.GET_LOGIN);
verify(request).getParameter(ConstantApp.RegistrationConstantField.GET_EMAIL);
verify(request, Mockito.atLeast(2)).getParameter(ConstantApp.RegistrationConstantField.GET_PASSWORD);
verify(request).getParameter(ConstantApp.RegistrationConstantField.GET_CONFIRM_PASSWORD);
}
#Test
public void shouldReturnTrue_WhenWeGetValidField() throws Exception{
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_FIRST_NAME)).thenReturn("Aloha");
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_LAST_NAME)).thenReturn("Dance");
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_LOGIN)).thenReturn("AlohaDance123");
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_EMAIL)).thenReturn("aloha.dance#gmail.com");
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_PASSWORD)).thenReturn("12345678Aa$");
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_CONFIRM_PASSWORD)).thenReturn("12345678Aa$");
Validation validation = new Validation();
Map<String, String> errorMap = validation.validate(new RegistrationInfoImpl(request));
assertTrue(errorMap.isEmpty());
}
My Exception:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/ServletException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at org.mockito.cglib.core.ReflectUtils.addAllMethods(ReflectUtils.java:349)
at org.mockito.cglib.proxy.Enhancer.getMethods(Enhancer.java:427)
at org.mockito.cglib.proxy.Enhancer.generateClass(Enhancer.java:457)
at org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217)
at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
at org.mockito.internal.creation.cglib.ClassImposterizer.createProxyClass(ClassImposterizer.java:123)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:57)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
at org.mockito.Mockito.mock(Mockito.java:1285)
at org.mockito.Mockito.mock(Mockito.java:1163)
at servlet.RegistrationServletTest.<init>(RegistrationServletTest.java:25)

Related

java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/jms/JMSException

im getting the below issue when i run junit test cases, the class is as follow:;
public class RoeSubmissionBeanTest {
RoeSubmissionBean roeSubmissionBean;
ServiceActivation serviceAct = new ServiceActivation();
UpdateTimeResponse updateTimeResponse = new UpdateTimeResponse();
RoEUpdateSuccessfulDT roeUpdateSucces;
MessageIdentification msgID;
ExchangeFaultData faultMessage;
#Before
public void setUp() throws Exception {
//it failes on this line
roeSubmissionBean = Mockito.mock(RoeSubmissionBean.class);
serviceAct = Mockito.mock(ServiceActivation.class);
updateTimeResponse = Mockito.mock(UpdateTimeResponse.class);
roeUpdateSucces = Mockito.mock(RoEUpdateSuccessfulDT.class);
doCallRealMethod().when(roeSubmissionBean).sendMessage(roeUpdateSucces, msgID, faultMessage);
}
and the main methods is
public class RoeSubmissionBean {
private Logger logger = LoggerFactory.getLogger(RoeSubmissionBean.class);
private JMSSender sender = new JMSSender(RoeSubmissionBean.class);
}
i tried some questions here that i have to put dependency in POM, but still getting same error
Error:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/jms/JMSException
{ at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at org.mockito.cglib.core.ReflectUtils.addAllMethods(ReflectUtils.java:349)
at org.mockito.cglib.proxy.Enhancer.getMethods(Enhancer.java:422)
at org.mockito.cglib.proxy.Enhancer.generateClass(Enhancer.java:457)
}

java.lang.ClassNotFoundException: org.junit.runners.BlockJUnit4ClassRunner

I have no problem executing this Junit (junit-4.4) of a spring 3.2.8 project from Eclipse, (Click right button -> Run As -> Junit Test)
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class AccomodationTypeDaoTest extends BaseDaoTest {
private AccomodationTypeDao accTypeDao;
#Test
public void testFindAll() {
assertNotNull(accTypeDao.findAll());
}
#Autowired
public void setAccomodationTypeDao(AccomodationTypeDao daoInstance) {
this.accTypeDao = daoInstance;
}
}
#SuppressWarnings("deprecation")
public class BaseDaoTest extends AbstractAnnotationAwareTransactionalTests {
private static final String[] CONFIG_LOCATIONS = new String[] { "classpath:com/dao/testDataAccessContext.xml" };
#Override
protected String[] getConfigLocations() {
return CONFIG_LOCATIONS;
}
#Test
public void testBaseDaoTest() {
assertTrue(true);
}
}
I have no problem as well, doing the same with all the classes form the package.
But when I click in the test folder /MyProject/MyProjectWeb/test/src I got this exception:
java.lang.TypeNotPresentException: Type [unknown] not present
at sun.reflect.annotation.TypeNotPresentExceptionProxy.generateException(TypeNotPresentExceptionProxy.java:46)
at sun.reflect.annotation.AnnotationInvocationHandler.invoke(AnnotationInvocationHandler.java:75)
at com.sun.proxy.$Proxy6.value(Unknown Source)
at org.junit.internal.requests.ClassRequest.getRunnerClass(ClassRequest.java:49)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:28)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
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.NoClassDefFoundError: org/junit/runners/BlockJUnit4ClassRunner
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
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)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:270)
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.annotation.AnnotationParser.parseSig(AnnotationParser.java:390)
at sun.reflect.annotation.AnnotationParser.parseClassValue(AnnotationParser.java:371)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:300)
at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:241)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:88)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:70)
at java.lang.Class.initAnnotationsIfNecessary(Class.java:3217)
at java.lang.Class.initAnnotationsIfNecessary(Class.java:3224)
at java.lang.Class.initAnnotationsIfNecessary(Class.java:3224)
at java.lang.Class.getAnnotation(Class.java:3176)
at org.junit.internal.requests.ClassRequest.getRunnerClass(ClassRequest.java:45)
... 9 more
Caused by: java.lang.ClassNotFoundException: org.junit.runners.BlockJUnit4ClassRunner
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)
... 37 more
From the javadoc of BlockJUnit4ClassRunner:
/**
* [...]
* </ul>
*
* #since 4.5
*/
public class BlockJUnit4ClassRunner
So it's not available in 4.4, you probably can upgrade to 4.11 without any code change

Exception in thread "main" java.lang.ClassNotFoundException: Main

Below is my code in IntelliJ
package com.example.helloWorld;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
I got an error as below
Exception in thread "main" java.lang.ClassNotFoundException: Main
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:`enter code here`308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:260)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:116)
Process finished with exit code 1
Kindly advice

Error parsing JSON in Java: ClassNotFoundException

I'm trying to parse a bit of JSON in Java by following this tutorial. Because it mentions nothing about org.apache.commons.io.IOUtils other than it imports it, I figured all it was used for it to convert an InputStream into a String. I have my own code for that, so I omitted it. Here is my code:
import java.io.*;
import java.io.InputStream;
import java.net.*;
import java.util.Scanner;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class Net {
static String returnParsedIp() throws UnsupportedEncodingException, MalformedURLException, IOException {
String url = "http://httpbin.org/ip";
URLConnection connection = new URL(url).openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
InputStream response = connection.getInputStream();
String responseString = new Scanner(response,"UTF-8").useDelimiter("\\A").next();
//return responseString;
JSONObject json = (JSONObject) JSONSerializer.toJSON(responseString);
String Ip = json.getString("origin");
return Ip;
}
}
I then call the method from my main class with:
public class DDNS {
public static void main(String[] args) throws Exception {
String Ip = Net.returnParsedIp();
System.out.println(Ip);
}
}
However, it throws the following error:
run:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
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)
at ddns.Net.returnParsedIp(Net.java:19)
at ddns.DDNS.main(DDNS.java:6)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
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)
... 14 more
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Any help is appreciated.
Either you don't have the Apache Commons lang and io JARs in your CLASSPATH or you have the wrong version.
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
This is Java 101. You need all the dependencies in the CLASSPATH in order to compile and run.
You have to add the commons-lang jar in yout project

Gdata API blogger example

I'm having trouble running this sample code for the gdata java library:
import java.net.URL;
import com.google.gdata.client.Query;
import com.google.gdata.client.blogger.BloggerService;
import com.google.gdata.data.Feed;
public class AccessBloggerSample {
public static void main(String[] args) throws Exception {
BloggerService service = new BloggerService("Testing-Blogger");
service.setUserCredentials("tmerachli#gmail.com", "XXX");
System.out.println("Google: " + BloggerService.getVersion());
URL feedUrl = new URL("http://minhchaunyc.blogspot.com/feeds/posts/default ");
Query query = new Query(feedUrl);
System.out.println("service: ");
Feed resultFeed = service.getFeed(query, Feed.class);
System.out.println("blogs: " + resultFeed.getEntries().size());
}
}
And I get the following error:
java.lang.NoClassDefFoundError: com/google/common/collect/Maps
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:118)
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:100)
at com.google.gdata.client.Service.<clinit>(Service.java:555)
at AccessBloggerSample.main(AccessBloggerSample.java:23)
Caused by: java.lang.ClassNotFoundException: com.google.common.collect.Maps
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:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:118)
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:100)
at com.google.gdata.client.Service.<clinit>(Service.java:555)
at AccessBloggerSample.main(AccessBloggerSample.java:23)
at __SHELL0.run(__SHELL0.java:6)
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:601)
at bluej.runtime.ExecServer$3.run(ExecServer.java:724)`
Any ideas why I'm getting this? I'm compiling and running my code through BlueJ and I extracted all the jar files into the lib directory of BlueJ and the code compiles.
You need to add guava to your Java Build-Patproject: http://code.google.com/p/guava-libraries/

Categories