0 0

SpringMVC JUnit单元测试问题5

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:config/system/applicationContext.xml", "classpath:config/system/spring-servlet.xml"})
public class UnitTest {
	
	@Autowired  
    private WebApplicationContext wac;
	
	@Test
	public void serverTest() throws Exception {
		System.out.println(wac);
	}
}

 

为什么我打印wac 总是 null

这边是我在CSDN 的提问 http://bbs.csdn.net/topics/390524025?page=1#post-395098845

4个答案 按时间排序 按投票排序

0 0

要继承AbstractTransactionalJUnit4SpringContextTests这个类,就可以直接拿到ApplicationContext了。

2013年7月23日 12:18
0 0


package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
// no use @WebAppConfiguration  
@ContextConfiguration(locations={"classpath:config/system/applicationContext.xml", "classpath:config/system/spring-servlet.xml"})
public class UnitTest {
	
	@Autowired  
    private WebApplicationContext wac;
	
	@Test
	public void serverTest() throws Exception {
		System.out.println(wac);
	}
}


2013年7月23日 08:51
0 0

WebApplicationContext 是Spring的上下文  Bean存在上下文中的一个容器中
你要注入的是容器中的一个Bean, 而不是把整个容器注入

2013年7月23日 00:45
0 0

试试这个

public class PlanRunReportServiceTest extends AbstractDependencyInjectionSpringContextTests{
	@Resource
	private PlanRunReportSerivce planRunReportSerivce;
	
	@Override
	protected String[] getConfigLocations() {
		return new String[]{"applicationContext.xml"};
	}
	
	public void onSetUp(){
		planRunReportSerivce = (PlanRunReportSerivce)this.applicationContext.getBean("planRunReportSerivce");
	}
}

2013年7月22日 15:27

相关推荐

Global site tag (gtag.js) - Google Analytics