4

i am working on a spring 3 web service application and on it i am trying to load the ApplicationContext from my servlett.xml file for use with a simple test case and it doesnt work.

ApplicationContext is always null.

this is my test code:

@RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "file:war/WEB-INF/FreedomSpring-servlett.xml" })
    public class UserControllerTest {

        private UserController controller;

        @Inject
        private ApplicationContext applicationContext;

        private String jsonUser = "{ \"username\":\"jonneymendoza\",\"emailAddress\":\"[email protected]\", \"password\":\"12345678\",\"firstName\":\"jono\", \"surname\":\"richy\", \"country\":\"united kingdom\",\"bio\":\"Bio stuff goes here about the user. where he comes from etc etc. all is well. lets go go go\" }";

        @Before
        public void setup() {
            controller = new UserController();

            assertNotNull(applicationContext);

        }

        @Test
        public void testLogin() {
            fail("Not yet implemented");
        }

        @Test
        public void testCreateNewAccount() {

            ResponseEntity<String> response = controller
                    .createNewAccount(new HttpEntity<String>(jsonUser));
            assertEquals(HttpStatus.CREATED, response.getStatusCode());

        }

        @Test
        public void testGetUserProfile() {
            fail("Not yet implemented");
        }

    }

It fails on setup as applicationContext is null. i want to basicaly load up my beans on this test case and use them here but autowiring the UserService class object as shown below in my controller class.

@Controller
public class UserController {
    @Autowired
    private UserService userService;

xml file that defines my service beans:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">


    <!-- Define services here-->

    <bean id="userService" class="com.jr.freedom.user.UserService"></bean>



</beans>

servett below:

<?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"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans      
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <import resource="mvc-config.xml" />

    <import resource="service-config.xml" />

    <import resource="datasource-config.xml" />

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>database.properties</value>
            </list>
        </property>
    </bean>

    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

    <context:component-scan base-package="com.jr.freedom.controllers"></context:component-scan>


</beans>

What am i missing?

edit: i am npw getting this error in the console output

java.lang.NoSuchMethodError: org.junit.runner.notification.RunNotifier.testAborted(Lorg/junit/runner/Description;Ljava/lang/Throwable;)V at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:146) at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61) at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:54) at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34) at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44) at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:52) 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)

Another edit: fixed the above junit error by using junit 4.4 instead. Now we are back to the original issue in regards to the ApplicatyionContext.

this is the error stack trace whenever i run my test:

log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
java.lang.NoClassDefFoundError: javax/servlet/ServletException
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
    at java.lang.Class.getDeclaredMethods(Class.java:1791)
    at org.springframework.core.type.StandardAnnotationMetadata.hasAnnotatedMethods(StandardAnnotationMetadata.java:136)
    at org.springframework.context.annotation.ConfigurationClassUtils.isLiteConfigurationCandidate(ConfigurationClassUtils.java:105)
    at org.springframework.context.annotation.ConfigurationClassUtils.checkConfigurationClassCandidate(ConfigurationClassUtils.java:86)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:216)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:178)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:617)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:96)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:44)
    at org.springframework.test.context.TestContext.buildApplicationContext(TestContext.java:198)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:233)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:126)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:85)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:95)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:139)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 42 more
11
  • If you're using a file you'd likely need to make sure that either (a) you've explicitly set the test execution directory, or (b) specify the complete pathname. IMO it's much easier to just use a classpath resource. Commented Jun 21, 2012 at 13:42
  • Can you see the log while your app is trying to build the ApplicationContext ? There must be some error, and you could get help from that log. Commented Jun 21, 2012 at 13:42
  • i have specified the complete pathname under "file:war/WEB-INF/FreedomSpring-servlett.xml" but it doesnt seem to work? Commented Jun 21, 2012 at 14:06
  • @DaveNewton the problem with that is that WEB-INF is not on the classpath. Commented Jun 21, 2012 at 14:29
  • yea it is not in the classpath. this is the standard way of creating a simple spring mvc/web service Commented Jun 21, 2012 at 14:35

3 Answers 3

2

Not really an answer, but hopefully it will help you troubleshoot (it did for me). Add @RunWith(SpringJUnit4ClassRunner.class) to your class like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:///c:/project/target/META-INF/spring/applicationContext.xml"})
public class SpringContextTest {
   ...
}

This will at least give you the logging, so it will be easier to see what's going on. Either it's incorrect file path, or a problem inside the context definition, e.g. an invalid bean definition.

NB: Nevermind the absolute path in my example, this was part of an experiment - it should really rely on a classpath: location.

UPDATE: The updated stacktrace suggests that you don't have the Java Servlets API on the classpath when running your tests (java.lang.NoClassDefFoundError: javax/servlet/ServletException). Make sure to include the jar servlet-api-2.5.jar (or similar) on the classpath.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. i now get this: Caused by: java.io.FileNotFoundException: class path resource [database.properties] cannot be opened because it does not exist which indicated that it cant find my database.properties file? its under the exact same location as the FreedomSpring-servlet.xml file under web-inf. see OP for full servlet.xml code. maybe i need to specify full path again?
Yes, but generally it will try to find properties on the classpath. Make sure it is on the classpath for tests.
Thanks mate. i fixed that but now getting another issue but anyways the initial problem of getting applicationContext is fixed therefore i will close this thread and mark your answer as the answered one. again thanks
1

It seems that the @RunWith(SpringJUnit4ClassRunner.class) annotation is missing, or was just a mistake when copy and paste?

Comments

1

I also struggled with this issue for 3-4 hours..but finally when I added the below code to my test class ....

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = { "file:///D:/PRMS_Workspace/PRMS/WebContent/WEB-INF/dispatcher-servlet.xml" }) 

It worked out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.