Java Spring Junit4TestRunner自动连线为空 应用程序上下文 测试上下文
如果我运行上述Junittestcase,autowire为空Java Spring Junit4TestRunner自动连线为空 应用程序上下文 测试上下文,java,spring,spring-mvc,spring-mvc-test,Java,Spring,Spring Mvc,Spring Mvc Test,如果我运行上述Junittestcase,autowire为空 如果我执行main方法并使用ClassPathXmlApplicationContext,bean正在加载,autowire不为null。问题似乎是您的测试用例中的cdiExample不是SpringBean。您正在@Before中手动实例化它 相反,请尝试以下方法: <import resource="classpath*:/beans.xml" /> 这样,cdiExample将从spring上下文中注入,spri
如果我执行main方法并使用ClassPathXmlApplicationContext,bean正在加载,autowire不为null。问题似乎是您的测试用例中的cdiExample不是SpringBean。您正在@Before中手动实例化它 相反,请尝试以下方法:
<import resource="classpath*:/beans.xml" />
这样,cdiExample将从spring上下文中注入,spring将自动连接dog 它不能为null,因为如果不能自动连接,spring将抛出异常。因此,您在运行测试用例时一定出了问题。
@Component
public class Dog implements Animal{
@Override public String getName() {
return "Puppy";
}
@Override public int getAge() {
return 10;
}
}
@Component("cdiExample")
public class CDIExample {
@Autowired
private Dog dog;
public void display() {
try {
System.out.println("com.example.Animal ---> " + dog.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:beans.xml");
Animal animal=context.getBean("dog", Animal.class);
System.out.println(animal.getName());
}
}
<context:annotation-config/>
<context:component-scan base-package="com.example"/>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:test-beans.xml" })
public class CDIExampleTest {
//@Autowired
private CDIExample cdiExample;
@Before
public void before() throws Exception {
cdiExample = new CDIExample();
}
@Test
public void testDisplay() throws Exception {
cdiExample.display();
}
}
<import resource="classpath*:/beans.xml" />
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:test-beans.xml" })
public class CDIExampleTest {
@Autowired
private CDIExample cdiExample;
@Test
public void testDisplay() throws Exception {
cdiExample.display();
}
}