Spring Test Class中的NullPointerException

Rob*_*use 1 junit spring annotations

我在测试Spring Junit测试配置时遇到了NullPointerException.问题在于使用@ContextConfiguration和@Autowired注释.

当我实例化上下文并直接获得对bean的引用时,如测试方法中注释掉的代码所示,测试正确运行并成功.但是当我尝试使用@ContextConfiguration和@autowired注释时,使用相同的XML文件属性,我在assertEquals语句中得到一个NullPointerException.你知道我做错了什么吗?

package com.greathouse.helloworld.HelloWorldTest;

import javax.inject.Inject;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import junit.framework.TestCase;

@ContextConfiguration(locations = {"classpath:/resources/application-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class AppTest extends TestCase
{
    @Autowired
    MessageService messageService;

    @Test
    public void testApp()
    {
        //ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/resources/application-config.xml");
        //messageService = context.getBean("printMessage", MessageService.class);
        assertEquals( messageService.getMessage(), "Hello World" );
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

看起来messageService没有自动装配.如果你根据需要放置messageService会有所帮助.

@Autowired( required = true )
Run Code Online (Sandbox Code Playgroud)

这种方式当spring上下文开始spring时会告诉你为什么它没有自动装配你的组件.另外作为旁注,由于您使用的是JUnit 4,因此您的测试不需要从TestCase扩展.

  • 我认为它默认设置为required = true? (3认同)