NoClassDefFoundError on org.springframework.boot.test.mock.mockito.MockReset - java

I am trying to write Junit for my Spring Boot REST application, but my test is failing with NoClassDefFoundError. Although, the jar is present in the classpath. I have tried multiple different annotations,but it is still failing at same place
Following are my classs
Application.java
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
#SpringBootApplication
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
BusinessServiceController.java
package com.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/business_services_WS")
public class BusinessServiceController {
Logger log = LoggerFactory.getLogger(BusinessServiceController.class);
/**
* 3.3.0 Request System Automation Limits [RSP-NSR]
* #author eaggatu
*/
#RequestMapping(value = "/number")
#PostMapping
public ResponseEntity<String> numberQueryResponse(#RequestBody String responseObj) {
log.info(responseObj);
return ResponseEntity.status(HttpStatus.OK).body("Number Search Query called");
}
}
Test Class
package com.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.context.WebApplicationContext;
import com.test.BusinessServiceController;
/*#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#SpringBootTest(classes={Application.class})
*/
#RunWith(SpringRunner.class)
#WebMvcTest(controllers = BusinessServiceController.class)
// #SpringBootTest(classes={Application.class})
#AutoConfigureMockMvc
public class CallBackResponseSimulatorTest {
#Autowired
private WebApplicationContext context;
#Autowired
private MockMvc mvc;
/*
* #Before public void setup(){ mvc =
* MockMvcBuilders.webAppContextSetup(context).build(); }
*/
#Test
public void callNumberSearchServiceSuccess() throws Exception {
this.mvc.perform(MockMvcRequestBuilders.post("/CallBackResponseSimulator/business_services_WS/number")
.contentType(MediaType.APPLICATION_JSON_UTF8).content("Hello! World"))
.andExpect(MockMvcResultMatchers.content().json("Number Search Query called"))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
Stack Trace
java.lang.IllegalAccessError: tried to access method org.mockito.internal.util.MockUtil.<init>()V from class org.springframework.boot.test.mock.mockito.MockReset
at org.springframework.boot.test.mock.mockito.MockReset.<clinit>(MockReset.java:56)
at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.beforeTestMethod(ResetMocksTestExecutionListener.java:45)
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:269)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
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)
java.lang.NoClassDefFoundError: Could not initialize class org.springframework.boot.test.mock.mockito.MockReset
at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.afterTestMethod(ResetMocksTestExecutionListener.java:50)
at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:319)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:94)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
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)
Build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'
jar {
baseName = 'gs-rest-service'
version = '0.1.0'
}
repositories {
mavenCentral()
jcenter()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
compile("org.springframework.boot:spring-boot-starter-web")
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
compile('org.springframework.boot:spring-boot-starter-test')
compile 'junit:junit:4.12'
compile group: 'org.mockito', name: 'mockito-core', version: '2.2.7'
}

Remove junit and mockito dependencies spring-boot-starter-test will provide the rights versions of these dependencies.
spring-boot-starter-test will add junit:4.12 and mockito:2.2.29

Another option is to remove the test execution listeners of your test class, annotating the class with #TestExecutionListeners.
Like this:
#RunWith(SpringRunner::class)
#SpringBootTest
#ActiveProfiles("integration")
#TestExecutionListeners()
class MyIntegrationTest {
...
}

For me the answer to this error was to insert the following TestExecutionListeners declaration at the top of my test case.
#RunWith(SpringRunner.class)
#TestExecutionListeners(listeners = {SpringBootDependencyInjectionTestExecutionListener.class, ServletTestExecutionListener.class})
public class MyUnitTest {

Related

Spring doesn't work with cucumber #ScenarioScope (IllegalStateException: No Scope registered for scope name 'cucumber-glue')

I have Cucumber tests. The stack for framework is Cucumber 6 / Junit 4.13 / Spring 5.2 / Spring-boot-starter 2.3.
For running Cucumber tests in parallel I use #ScenarioScope annotation to make autowiring instances to be recycled between scenarios.
Tests launch fine when I use CucumberRunner. E.g.:
#RunWith(Cucumber.class)
#CucumberOptions(
plugin = {"pretty", "html:target/cucumber-reports.html"},
features = {"classpath:features"},
glue = {"<some_glue_class>"})
public class CucumberRunnerTest {
}
But when I try run some Junit tests (only, without Cucumber) I get an error.
E.g. Context:
#Configuration
#Import({BeanConfigClass.class})
public class DefaultContext {
// ...
}
Instance:
#ScenarioScope
#Component
public class Foo {
// ...
}
Test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = DefaultContext.class)
public class SomeTest {
#Autowired
private Foo foo;
#Test
public void fooTest(){
//some test
}
}
Error:
java.lang.IllegalStateException: No Scope registered for scope name 'cucumber-glue'
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:357)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:675)
at Foo$$EnhancerBySpringCGLIB$$1cf6c75d.replace(<generated>)
at test.SomeTest.fooTest(SomeTest.java:16)
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:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
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:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
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$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Question:
I understand that I need to use a kind of CucumberRunner to make Spring understand cucumber-glue scope. But how to implement it?
I would have the ability to create specific bean, but the class CucumberScenarioScope is package-private in io.cucumber.spring. So it doesn't work:
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static io.cucumber.spring.CucumberTestContext.SCOPE_CUCUMBER_GLUE;
import static io.cucumber.spring.CucumberScenarioScope; //is not visible!
#Configuration
public class CustomScopeConfig {
#Bean
public BeanFactoryPostProcessor beanFactoryPostProcessor(){
return factory -> factory.registerScope(SCOPE_CUCUMBER_GLUE, new CucumberScenarioScope());
}
}

Cant apply rest controllers junit tests correctly

I am trying to apply junit test for my rest controllers.
I've tried to apply junit 4 but I got 404 error instead 200.
It looks like something is not initialized but cant't figured what.
Here is tutorial I have tried to apply.
https://www.youtube.com/watch?v=8S8o46avgAw
I also tried some different tutorials with junit 5 but the result was the same.
Here you can find the whole project.
https://github.com/WojciechWeg/tiny-bank/tree/tests
Just before publishing this post I've applied the following:
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(customerController)
.build();
customer = new Customer("Jan","Kowalski",new Date(),"Marszalkowska",new ArrayList<>());
customerService.createNewCustomer(customer);
System.out.println("Customers from service: "+ customerService.getAllCustomers());
}
But the result of it is:
Customers from service: []
So it returns nothing. Above snippet is not in repo link.
Rest controller class:
package com.tinybank.tinybankapi.controllers;
import com.tinybank.tinybankapi.model.Account;
import com.tinybank.tinybankapi.model.Customer;
import com.tinybank.tinybankapi.model.CustomerResource;
import com.tinybank.tinybankapi.services.CustomerService;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resources;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.util.List;
#RestController
#RequestMapping(CustomerController.BASE_URL)
public class CustomerController {
public static final String BASE_URL = "api/customers";
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
#GetMapping
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<Resources<List<Customer>>> getListOfCustomers() {
Resources<List<Customer>> resources = new Resources(customerService.getAllCustomers());
String uri = ServletUriComponentsBuilder.fromCurrentRequest().build().toUriString();
resources.add(new Link(uri,"self"));
return ResponseEntity.ok(resources);
}
#GetMapping({"/{id}"})
#ResponseStatus(HttpStatus.OK)
public Customer getCustomer(#PathVariable Long id) {
return customerService.getCustomerById(id);
}
#DeleteMapping({"/{id}"})
#ResponseStatus(HttpStatus.OK)
public void deleteCustomer(#PathVariable Long id) {
customerService.deleteCustomerById(id);
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<CustomerResource> createNewCustomer(#RequestBody #Valid Customer Customer) {
Customer customer = customerService.createNewCustomer(Customer);
URI uri = MvcUriComponentsBuilder.fromController(getClass())
.path("/{id}")
.buildAndExpand(customer.getId())
.toUri();
return ResponseEntity.created(uri).body(new CustomerResource(customer));
}
#PutMapping({"/{id}/open_account"})
#ResponseStatus(HttpStatus.OK)
public void openAccount(#PathVariable Long id, #RequestBody Account account) {
customerService.openAccount(id, account);
}
}
Test class:
package com.tinybank.tinybankapi.controllers;
import com.tinybank.tinybankapi.model.Customer;
import com.tinybank.tinybankapi.services.CustomerService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.Date;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringJUnit4ClassRunner.class)
public class CustomerControllerTest {
private MockMvc mockMvc;
#Mock
private CustomerService customerService;
#InjectMocks
private CustomerController customerController;
Customer customer;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(customerController)
.build();
customer = new Customer("Jan","Kowalski",new Date(),"Marszalkowska",new ArrayList<>());
customerService.createNewCustomer(customer);
System.out.println("Customers from service: "+ customerService.getAllCustomers());
}
#Test
public void getCustomer() throws Exception {
when(customerService.getCustomerById(any())).thenReturn(customer);
mockMvc.perform(get("api/customers/1"))
.andExpect(status().isOk());
}
}
This is how stack trace looks like:
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
at com.tinybank.tinybankapi.controllers.CustomerControllerTest.getCustomer(CustomerControllerTest.java:53)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
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:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Have you tried below approach without injecting mocks?
MockMvcBuilders.standaloneSetup(new CustomerController())
.build();
EDIT:
I've ran your code locally.
Do this:
mockMvc = MockMvcBuilders.standaloneSetup(new CustomerController(customerService))
.build();
And add slash to the beginning of URL
mockMvc.perform(get("/api/customers/1"))
.andExpect(status().isOk());

ArrayIndexOutOfBoundsException when accessing the getter on an object created by Spring's class converter

I'm converting one object to another object, but when I try to use the getter on the object that was created, I'm getting an ArrayIndexOutOfBoundsException.
The data is a simple String in the field and is on a very straight-forward object.
I've gotten this same issue with both Spring Boot 2.1.1 & 2.1.7.
Note: To replicate the issue, I have to run using mvn test, mvn install, or use Eclipse' code coverage tool. Using Eclipse's Run or Debug utils succeeds without error.
Exception:
[ERROR] storeWithEncryption(com.forms.service.SpringConversionServiceTest) Time elapsed: 0.003 s <<< ERROR!
java.lang.ArrayIndexOutOfBoundsException: 1
at com.forms.service.SpringConversionServiceTest$To.<init>(SpringConversionServiceTest.java:45)
at com.forms.service.SpringConversionServiceTest.storeWithEncryption(SpringConversionServiceTest.java:26)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
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:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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:190)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:273)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)
Test Class
package com.forms.service;
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.core.convert.ConversionService;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.forms.Application;
#RunWith(SpringRunner.class)
#ActiveProfiles("test")
#SpringBootTest(classes = { Application.class })
public class SpringConversionServiceTest {
#Autowired
private ConversionService conversionService;
#Test
public void storeWithEncryption() throws Exception {
From from = new From();
from.bob = "nope";
from.bob2 = "yep";
new To(conversionService.convert(from, To.class));
}
public static final class From {
String bob;
String bob2;
}
public static final class To {
public To() {
// TODO Auto-generated constructor stub
}
public To(To convert) {
this.bob = convert.bob;
this.bob2 = convert.bob2;
}
String bob;
String bob2;
}
}
FromToConverter
package com.forms.service;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import com.forms.service.SpringConversionServiceTest.From;
import com.forms.service.SpringConversionServiceTest.To;
import com.forms.service.converter.AbstractReflectionConverter;
#Component
public class FromToConverter extends AbstractReflectionConverter implements Converter<From, To> {
public To convert(From from) {
To to = new To();
try {
// 1 to 1 conversions
conversionByReflection(from, to);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("The source external Header cannot be converted into an internal Header", e);
}
return to;
}
}
Application.java
package com.forms;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
#SpringBootApplication
#ImportResource({ "classpath:spring/camel-context.xml" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Pom:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
</parent>
In order to get around this issue, I had to change from using spring's reflective ConversionService methods to just manually plugging in the values in the converter.
I won't be marking this as the solution as it doesn't really fix the issue if you need to use reflection, but I'm putting it here to serve as a work-around.

SpringBoot Application with Gradle fails with ./gradlew bootRun

I am running into an issue attempting to build an introductory application using SpringBoot.
I am using Gradle as my build management tool
build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
}
}
plugins {
id 'org.springframework.boot' version '2.0.4.RELEASE'
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'sia'
version = '0.0.1-SNAPSHOT'
description = "taco-cloud"
bootJar {
baseName = 'taco-cloud'
version = '0.1.0'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/milestone" }
maven { url "http://repo.maven.apache.org/maven2" }
}
dependencies {
compile group: 'org.springframework.boot', name: "spring-boot-starter-data-jpa"
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version:'2.0.0.M3'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version:'2.0.0.M3'
runtime group: 'org.springframework.boot', name: 'spring-boot-devtools', version:'2.0.0.M3'
//providedRuntime group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat'
testCompile(group: 'org.springframework.boot', name: 'spring-boot-starter-test', version:'2.0.0.M3') {
exclude(module: 'commons-logging')
}
}
I am pretty sure that should cover most of the dependencies. I have just a couple classes and a couple tests.
Driver
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package tacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class TacoCloudApplication {
public static void main(String[] args) {
SpringApplication.run(TacoCloudApplication.class, args);
}
}
Controller
package tacos;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class HomeController
{
#GetMapping("/")
public String home()
{
return "home";
}
}
Driver Test
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package tacos;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
//import static org.junit.Assert.*;
#RunWith(SpringRunner.class)
#SpringBootTest
public class TacoCloudApplicationTest {
#Test
public void contextLoads() {
}
}
Controller Test
package tacos;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
#RunWith(SpringRunner.class)
#WebMvcTest(HomeController.class)
public class HomeControllerTest
{
#Autowired
private MockMvc mockMvc;
#Test
public void testHomePage() throws Exception
{
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("home"))
.andExpect(content().string(containsString("Welcome to ...")));
}
}
This should be a super simple application but I seem to have a missing dependency or some other issue where SpringApplication.run fails to happen. I have looked at other posts that are similar but the solutions given don't make much sense. The error I get from the test is:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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:190)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
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.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy1.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
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.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:146)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:128)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
The error using ./gradlew bootRun is similar since the application context never loads. Really confused as this was supposed to be a no-brainer intro exercise. The original exercise is a maven build, so I am not sure if that makes any difference here.
Super stuck....
With the help of #Rcordoval and this post I was able to resolve the issues with both the test and the failure of the bootRun task.
I needed to address what autoconfigure is attempting. This also is trying to configure a jdbc DB. So I had to update the driver class as with a couple imports and a new annotation to exclude trying to configure the DB.
package tacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
#SpringBootApplication
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class TacoCloudApplication {
public static void main(String[] args) {
SpringApplication.run(TacoCloudApplication.class, args);
}
}
Finally, the linked post pointed me to the last issue of the bootRun task. I simply removed the version from the build.gradle for spring-boot-devtools dependency. Now the application boots in tomcat and tests pass.

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

Categories

Resources