ApplicationContext始终为null

时间:2012-06-21 13:24:14

标签: java unit-testing servlets spring-3 applicationcontext

我正在开发一个Spring 3 Web服务应用程序,并且我正在尝试从我的servlett.xml文件加载ApplicationContext以用于一个简单的测试用例,但它不起作用。

ApplicationContext始终为null。

这是我的测试代码:

@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\":\"jon@google.com\", \"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");
        }

    }

设置失败,因为applicationContext为null。我想基本上在这个测试用例中加载我的bean并在这里使用它们,但是在我的控制器类中如下所示自动装配UserService类对象。

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

定义我的服务bean的xml文件:

<?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>

下面的服务:

<?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>

我缺少什么?

编辑:我在控制台输出中发现此错误

  

java.lang.NoSuchMethodError:   org.junit.runner.notification.RunNotifier.testAborted(Lorg / junit的/流道/描述; Ljava /郎/ Throwable的;)V     在   org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:146)     在   org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61)     在   org.junit.internal.runners.JUnit4ClassRunner $ 1.run(JUnit4ClassRunner.java:54)     在   org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)     在   org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)     在   org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:52)     在   org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)     在   org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

另一个编辑:通过使用junit 4.4修复了上述junit错误。现在我们回到关于ApplicatyionContext的原始问题。

这是我运行测试时的错误堆栈跟踪:

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

3 个答案:

答案 0 :(得分:2)

不是真正的答案,但希望它能帮助您排除故障(它对我有用)。像这样在您的班级中添加@RunWith(SpringJUnit4ClassRunner.class)

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

这至少会为您提供日志记录,因此可以更轻松地查看正在进行的操作。它是不正确的文件路径,还是上下文定义中的问题,例如:无效的bean定义。

注意:在我的例子中没关系绝对路径,这是实验的一部分 - 它应该真正依赖于classpath:位置。

更新:更新的堆栈跟踪表明在运行测试时,类路径上没有Java Servlets API(java.lang.NoClassDefFoundError:javax / servlet / ServletException)。确保在类路径中包含jar servlet-api-2.5.jar(或类似的)。

答案 1 :(得分:1)

我也在这个问题上挣扎了3-4个小时..但最后我将以下代码添加到我的测试类中....

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

它成功了。

答案 2 :(得分:0)

似乎缺少@RunWith(SpringJUnit4ClassRunner.class)注释,或者复制和粘贴时只是一个错误?