junit: NullPointer on injected bean when testing controller with mockmvc - java

So I have this test case:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:rest-context-test.xml")
public class CustomerControllerTest {
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders
.standaloneSetup(new CustomerController()).build();
}
#Test
public void testGetCustomerById() throws Exception {
mockMvc.perform(get("/customers/{ccid}", 1)).andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$.ccid").value("1"));
}
}
That loads rest-context-test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<bean id="customerServiceImpl"
class="myorg.service.impl.MockCustomerServiceImpl" />
</beans>
With the hope of being able to AutoWire customerServiceImpl into my controller:
#Controller
#RequestMapping("customers")
public class CustomerController {
private static Logger Logger = LoggerFactory
.getLogger(CustomerController.class);
#Autowired
#Qualifier("customerServiceImpl")
private CustomerService customerService;
#RequestMapping(value = "/{ccid}", method = RequestMethod.GET, produces = "application/json")
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public Customer getCustomerById(#PathVariable Integer ccid)
throws BadRequestException, ServerErrorException,
ResourceNotFoundException {
Customer c = null;
try {
c = customerService.getCustomer(ccid);
} catch (IllegalArgumentException iae) {
// HTTP 400
Logger.error("Invalid arguments submitted", iae);
throw new BadRequestException();
} catch (CsspException ce) {
// HTTP 500
Logger.error("Server error", ce);
throw new ServerErrorException();
}
if (c == null) {
// HTTP 404
throw new ResourceNotFoundException();
}
return c;
}
}
But my unit test is throwing the following trace:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:168)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:136)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:141)
at myorg.rest.controller.CustomerControllerTest.testGetCustomerById(CustomerControllerTest.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at 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.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:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
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.NullPointerException
at myorg.rest.controller.CustomerController.getCustomerById(CustomerController.java:134)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle (ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod (RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal (RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
... 38 more
This null pointer is thrown when the Controller tries to access customerService:
#Autowired
#Qualifier("customerServiceImpl")
private CustomerService customerService;
Why isn't my MockCustomerServiceImpl being AutoWired into the Controller?
Note: package names have been changed to protect the innocent

From Spring documentation:
The "webAppContextSetup" loads the actual Spring MVC configuration resulting in a more complete integration test. Since the TestContext framework caches the loaded Spring configuration, it helps to keep tests running fast even as more tests get added. Furthermore, you can inject mock services into controllers through Spring configuration, in order to remain focused on testing the web layer.
The "standaloneSetup" on the other hand is a little closer to a unit test. It tests one controller at a time, the controller can be injected with mock dependencies manually, and it doesn’t involve loading Spring configuration. Such tests are more focused in style and make it easier to see which controller is being tested, whether any specific Spring MVC configuration is required to work, and so on. The "standaloneSetup" is also a very convenient way to write ad-hoc tests to verify some behavior or to debug an issue.
From this I understand that, if I need an .xml as a Spring configuration file to be loaded, then I need to go with the "webAppContextSetup". If I just need very simple tests with my Controller, without the need of a Spring configuration, then I go with the "standaloneSetup" approach. In your case, I think you need the "webAppContextSetup".

You forgot to create your mock objects and then inject them into your controller like so
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:rest-context-test.xml")
public class CustomerControllerTest
{
#Mock
private CustomerService customerService;
#InjectMocks
private CustomerController customerController;
private MockMvc mockMvc;
#Before
public void setup()
{
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders
.standaloneSetup(customerController).build();
}
#Test
public void testGetCustomerById() throws Exception
{
mockMvc.perform(get("/customers/{ccid}", 1)).andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$.ccid").value("1"));
}
}

It helped me to fix the NullPointerException by adding annotations #RunWith(SpringRunner.class) ,#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) and #AutoConfigureMockMvc
Here is code that worked for me-
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#AutoConfigureMockMvc
public class MyTestClass {
#Autowired
private MockMvc mockMvc;
#Test
public void myClassController() throws Exception {
Object obj = new Object();
obj.setA(1);
obj.setB(2);
obj.setC(3);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(obj); // this is the json body
mockMvc.perform(post("/ENDPOINT")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonString))
.andDo(print())
.andExpect(status().isOk());
}

Related

Spring MVC Test: java.lang.AssertionError: No ModelAndView found

I'm novice to all this stuff, writing test for Spring MVC controller and got error above, tried solution provided in
Spring 3.2.5 error "java.lang.AssertionError: No ModelAndView found" for all my controller Unit Test - still no luck! Could pls anyone help? Thanks in advance!
let me know if anything else needed on top of code below.
test class:
(note, that printout of getBeanDefinitionNames() among others returns "homeController" - so I assume controller is found and initialized )
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes={WebDispatcherConfig.class,DataConfig.class})
#WebAppConfiguration
public class HomeControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext wac ;
#Before
public void setUp() {
this.mockMvc = webAppContextSetup(wac).build();
System.out.println(Arrays.toString(wac.getBeanDefinitionNames()));
}
#Test
public void testHome() throws Exception {
mockMvc
.perform(get(WebDispatcherConfig.WEBAPP_PREFIX))
.andExpect(view().name(HomeController.HOME))
.andExpect(model().attributeExists(WebDispatcherConfig.PREFIX_NAME));
}
}
web context config class:
#EnableWebMvc
#ComponentScan("io.github.d2edev.mywebapp.web")
public class WebDispatcherConfig extends WebMvcConfigurerAdapter {
public static final String WEBAPP_PREFIX="/web";
public static final String PREFIX_NAME="wepbrefix";
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
controller (note it's already in package reflected in #ComponentScan in config class above):
package io.github.d2edev.mywebapp.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import io.github.d2edev.mywebapp.config.WebDispatcherConfig;
#Controller
#RequestMapping("/")
public class HomeController {
public static final String HOME="home";
#RequestMapping(method=RequestMethod.GET)
public String home(Model model){
model.addAttribute(WebDispatcherConfig.PREFIX_NAME, WebDispatcherConfig.WEBAPP_PREFIX);
return HOME;
}
}
stacktrace:
java.lang.AssertionError: No ModelAndView found
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:39)
at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:72)
at org.springframework.test.web.servlet.result.ViewResultMatchers$2.match(ViewResultMatchers.java:68)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at test.web.HomeControllerTest.testHome(HomeControllerTest.java:52)
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:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
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:193)
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)
Solved!
Reason is that in my real app servlet is mapped to "/web" and HomeController to "/" which results that controller serves requests to "/web".
So I provided same "/web" address for GET request in controller test class, but when we create MockMvc, as I understood, we can't make mapping like we do in app init class, so "test" controller was waiting for my request at "/".
To make it work, I should either explicitly put
.perform(get("/"))
or make on-fly remapping with additional code like proposed here:
MockMvc WebAppConfiguration: Load servlet mappings in web.xml
Thanks!

Java Spring MVC - java.lang.NoClassDefFoundError: javax/servlet/ServletContext

I am trying to write some JUnit testing for my Java Spring application but I keep getting this error java.lang.NoClassDefFoundError: javax/servlet/ServletContext.
Test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class SampleTest {
#Autowired
public ApplicationContext applicationContext;
#Test
public void sampleTest() throws Exception {
fail("this is a fail.");
}
}
pom.xml:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
AppConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"my.base.package"})
public class AppConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver res = new InternalResourceViewResolver();
res.setPrefix("/");
res.setSuffix(".jsp");
return res;
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("/i18/usermsg");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setDefaultLocale(new Locale("en_US"));
resolver.setCookieName("myLocaleCookie");
resolver.setCookieMaxAge(4800);
return resolver;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("mylocale");
registry.addInterceptor(interceptor);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Exception trace:
java.lang.NoClassDefFoundError: javax/servlet/ServletContext
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2442)
at java.lang.Class.getDeclaredMethods(Class.java:1808)
at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:140)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:290)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:230)
at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:486)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:276)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:230)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:197)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:166)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:306)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:239)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:68)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:86)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:259)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:261)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:219)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletContext
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)
... 49 more
This is my first time writing JUnit tests, so I don't know if you super-kind guys need extra information. If so, I would be glad to provide them :)
You need to use #WebAppConfiguration annotation in your test class. Here is what the documentation states:
#WebAppConfiguration A class-level annotation that is used to declare
that the ApplicationContext loaded for an integration test should be a
WebApplicationContext. The mere presence of #WebAppConfiguration on a
test class ensures that a WebApplicationContext will be loaded for the
test, using the default value of "file:src/main/webapp" for the path
to the root of the web application (i.e., the resource base path). The
resource base path is used behind the scenes to create a
MockServletContext which serves as the ServletContext for the test’s
WebApplicationContext.
This works with provided scope of javax.servlet-api.
Besides, you can't use #EnableWebMvc in the configuration class you use for testing. Best if you create a separate configuration class that will be only used for testing, without #EnableWebMvc. You can check out this discussion: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
Its dues to the value of the scope (provided) you have declared here. Try modifying it to test and it shall work well. But its recommended to keep provided since this jar file is provided by the servlet container by default.

how to test DAO Implementations methods in spring mvc with java configuration classes and no XML using jUnit

i'm working in a spring mvc project using netbeans i created a netbeans maven web project and i configured it to be a spring mvc project with java classes configuration and NO-XML, i'm trying to do a unit test of a insert DAO implementation method and my autowired DAO variable is always null
i was following this tutorial http://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles
here is my MvcConfig class
#Configuration
#ComponentScan("controller")
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
//JDBCTEMPLATE
#Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:#127.0.0.1:1521:XE");
dataSource.setUsername("myPC");
dataSource.setPassword("fakePassword");
return dataSource;
}
//CREATE DAO BEAN
#Bean
public UserDAO getUserDAO() {
return new UserDAOImplementation( getDataSource() );
}
}
here is my User DAO
public interface UserDAO{
public void insertUser(User user);
}
and my UserDAOImplementation
public class UserDAOImplementation implements UserDAO{
private JdbcTemplate jdbcTemplate;
public UserDAOImplementation () {}
public UserDAOImplementation (DataSource datasource) {
this.jdbcTemplate = new JdbcTemplate(datasource);
}
#Override
public void insertUser(User user) {
String sql = "INSERT INTO User"
+ "(field1, field2, field3, field4, field5, field6)"
+ " VALUES (SEQ_user.nextval, ?, ?, ?, ?, ?)";
jdbcTemplate.update(sql, user.getField1(),
user.getField2(),
user.getField3(),
user.getField4(),
user.getField5() );
}
}
and here is my test class i have commented "#RunWith(SpringJUnit4ClassRunner.class)" beacuse it gives me this error
org/junit/runners/model/MultipleFailureException
java.lang.NoClassDefFoundError
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.withAfterClasses(SpringJUnit4ClassRunner.java:187)
at org.junit.runners.ParentRunner.classBlock(ParentRunner.java:145)
at org.junit.runners.ParentRunner.run(ParentRunner.java:235)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.ClassNotFoundException: org.junit.runners.model.MultipleFailureException
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:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 16 more
this is my test class
// this is commented because it gives me errors #RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=MvcConfig .class, loader=AnnotationConfigContextLoader.class)
public class UserTest{
User user;
#Autowired
private UserDAO userDAO;
#Before
public void setUp() {
System.out.println("#Before - setUp");
user = new User();
user.setField1("a");
user.setField2("a");
user.setField3("a");
user.setField4("a");
user.setField5("a");
}
#Test
public void insertUser () {
userDAO.insertUser(user);
}
the AutoWired userDAO variable is always null
i'm running the test by right clicking it and choose run file
this are the imports i'm using
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
i'm using netbeans 8.0.2, my thoughts are that the problem is because i'm not using this #RunWith(SpringJUnit4ClassRunner.class) beacuse it gives me the errors that i mention before, but i dont know maybe i'm missing something, this insert method works fine outside the test i just wanted to test it to test some new methods in the future and i wanted to learn how to test methods with a java configuration
EDIT
i looked at my folder Test Depencies and inside my package org.junit.runners.model theres no a MultipleFailureException i dont know if that could be the error
EDIT 2
i updated my junit version from junit 4.7 to junit 4.12 and know i have this error ERROR: Failed to load ApplicationContext
Failed to load ApplicationContext
java.lang.IllegalStateException
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:91)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:74)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:116)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:82)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:199)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:251)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:253)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:216)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:82)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:60)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:67)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:63)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:83)
... 33 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 48 more
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:54)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:358)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$ae1586a5.CGLIB$defaultServletHandlerMapping$16(<generated>)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$ae1586a5$$FastClassBySpringCGLIB$$38361e62.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:311)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$ae1586a5.defaultServletHandlerMapping(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 49 more
i found the solution since my MvcConfig class have a #EnableWebMvc annotation
like this:
#Configuration
#ComponentScan("controller")
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
i needed to add this annotation to my test class #WebAppConfiguration and change the loader value from AnnotationConfigContextLoader to this AnnotationConfigWebContextLoader like this:
loader=AnnotationConfigWebContextLoader.class
so in conclusion i modified my test class like this:
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=MvcConfiguracion.class, loader=AnnotationConfigWebContextLoader.class)
public class UserTest{

Spring MVC testframework fails with HTTP Response 406

I started to use the new MVC Testframework of Spring 3.2 and got stuck with getting 406 HTTP Response Codes for all my test cases.
The testcase is plain simple
public class LocationResouceTest {
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
#Test
public void testGetLocationByPlzPattern() throws Exception {
// here I need to define the media type as a static var from MediaType
this.mockMvc.perform(get("/someurl?someparam=somevalue")).andExpect(status().isOk());
}
}
the corresponding resource is
#Controller
// here I need to define the media type as string
#RequestMapping(value = "/someurl", produces = "application/json; charset=UTF-8")
public class LocationResource {
#ResponseBody
#RequestMapping(method = RequestMethod.GET)
public ArrayList<DTO> getAllIndex(#RequestParam("someparam") String param) {
return ... //the list of DTO classes is transformed to json just fine if called with curl
}
}
I am sure it is because of a wrong media type but I cannot figure out why.
The trace of the failing testcase:
java.lang.AssertionError: Status expected:<200> but was:<406> at
org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at
org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at
org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:546)
at
org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
at
de.yourdelivery.rest.location.LocationResouceTest.testGetLocationByPlzPattern(LocationResouceTest.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at
org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at
org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at
org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at
org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at
org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
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)
If you have a #Configuration class, you can add the
#EnableWebMvc
annotation instead of using an XML configuration with <mvc:annotation-driven />.
It is necessary to have both #EnableWebMvc
and .accept(MediaType.APPLICATION_JSON)
This might be caused by not having any MVC configuration in the Spring test context. When using something like:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration("/test-context.xml")
...then that test-context.xml file should also include things like:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
<mvc:message-converters>
<bean id="..." class=
"org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean id="..."
class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean id="..."
class="org.springframework.http.converter.FormHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/json" />
<property name="mediaTypes">
<value>
json=application/json
xml=application/xml
</value>
</property>
</bean>
One can easily test if the above is the problem, with a controller that does not specify anything special (such as: no produces in #RequestMapping), and hence does not need any content negotiation:
#RequestMapping(value = "/foo", method = RequestMethod.GET)
#ResponseBody
public String getFoo() {
return "bar";
}
...with:
#Test
public void getFoo() throws Exception {
MvcResult result =
this.mockMvc.perform(get("/foo").accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk())
.andReturn();
Assert.assertEquals(result.getResponse().getContentAsString(), "bar");
}
You need to add the following code to spring xml to serialize POJO in jackson.
<annotation-driven />
You are missing the <mvc:annotation-driven /> in the configuration xml file.
The spring way of doing things is, i think, to use a HttpResponseEntity, or return a modelandview.
For example :
#ResponseBody
ResponseEntity<String> getFoo() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
String test = "{\"foo\":{\"title\": \"Stack\"}}";
return new ResponseEntity<String>(test, responseHeaders, HttpStatus.OK);
}
(I'd be interested in any further progress you make as its all pretty new)
I think the fix is to modify the request this way:
this.mockMvc.perform(get("/someurl?someparam=somevalue").contentType(MediaType.APPLICATION_JSON)).andExpect..
I met same problem just now, and is resolved by changing the return type of the Controller to String.
And return a JSON string instead of an object directly. It does works.
Gson gson = new Gson();
return gson.toJson(dto);

Spring ROO: JUnit test fails

I am having trouble executing my Spring IntegrationTests, when i run the code below it is failing at the persist method:
#RooIntegrationTest(entity = Person.class)
public class PersonIntegrationTest {
#Test
public void test() {
}
#Test
public void testCountPeople(){
Person personToPersist = PersonTestUtil.createTestPerson();
personToPersist.persist();
Long count = Person.countPeople();
assertNotNull(personToPersist);
assertTrue(personToPersist.countPeople() == 1);
}
}
The Stack trace is below
java.lang.IllegalStateException: Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethod$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$entityManager(Person_Roo_Entity.aj:95)
at org.bixin.dugsi.domain.Person.entityManager(Person.java:1)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethodDispatch1$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$entityManager(Person_Roo_Entity.aj)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethod$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$persist(Person_Roo_Entity.aj:58)
at org.bixin.dugsi.domain.Person.persist(Person.java:1)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethodDispatch1$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$persist(Person_Roo_Entity.aj)
at org.bixin.dugsi.domain.PersonIntegrationTest.testCountPeople(PersonIntegrationTest.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
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)
Anyone run into this problem?
It seems that you have not injected the EntityManager and the related application context to your test.
Please try adding the following line above the class declaration.
#ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml","/META-INF/spring/applicationContext-security.xml" })
and try making your test class to inhert from AbstractJUnit4SpringContextTests. Do keep in mind that you might have to implement authentication for some operations to be executed.
Your test class could look like below.
package com.myapp.test;
#ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml","/META-INF/spring/applicationContext-security.xml" })
public class TestMyService extends AbstractJUnit4SpringContextTests {
#Autowired
MyService service = new MyService();
private void setUp() {
//Do the setting up of your classes for the test
}
#Test
public void testOperation() throws IOException {
//My Test Code here
}
}
Note that you should generally have a different context for your testing purposes.
Cheers.
If you're using Springsource Tool Suite (or another Eclipse) try to clean the project. I think Eclipse someimes doesn't use the AJDT Compiler, specially at startup.
I don't remember this message from the Roo console, that uses maven under the hood.
Try "perform eclipse" from the Roo shell or even maven directly from the console (mvn clean install or something like that)
It seems that you forgot to inject the EntityManager and the application context.
Try something like this, it worked for me with Spring Roo:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.jitter.finance.analyzer.domain.Address;
#ContextConfiguration(locations = { "classpath*:/META-INF/spring/applicationContext*.xml"})
public class EmTest extends AbstractJUnit4SpringContextTests {
#Test
public void checkEm(){
Address a = new Address();
a.setName("Primo");
a.persist();
Address b = new Address();
b.setName("Secondo");
b.persist();
for(Address ad : Address.findAllAddresses()){
System.out.println(ad.getName());
assertEquals(ad.getName().charAt(ad.getName().length()-1), 'o');
}
}
}

Categories

Resources