用junit测试获取spring bean 报No Scope registered for scope 'session'错

spring 配置如下

 

 

 
   	 	
  	

 

 

测试类

 

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:WebRoot/WEB-INF/spring/*.xml"})
@TestExecutionListeners({ 
    WebContextTestExecutionListener.class, 
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class })
public class testi18n {
	
	@Autowired
	private I18nManager i18nManager;
	
	@Test
	public void test01(){
		i18nManager.setLocale(Locale.ENGLISH);
		System.out.println(i18nManager.getMessage("title"));;
	}
}

 

 

注意:需要在测试类头中加入

 

 

@TestExecutionListeners({ 
    WebContextTestExecutionListener.class, 
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class })

 是关键. 

 

 

 

其中的WebContextTestExecutionListener类需要在类路径中自行创建

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.SimpleThreadScope;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;

public class WebContextTestExecutionListener extends AbstractTestExecutionListener {
    @Override
    public void prepareTestInstance(TestContext testContext) throws Exception {

        if (testContext.getApplicationContext() instanceof GenericApplicationContext) {
            GenericApplicationContext context = (GenericApplicationContext) testContext.getApplicationContext();
            ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
            Scope requestScope = new SimpleThreadScope();
            beanFactory.registerScope("request", requestScope);
            Scope sessionScope = new SimpleThreadScope();
            beanFactory.registerScope("session", sessionScope);
        }
    }
}

 

ok .这样就可以使用junit 测试 scope 为request 或者 session的bean了

 =========================================================================

 

如果你没有使用spring-test框架

而是通过 XmlWebApplicationContext   ClassPathXmlApplicationContext  来获取上下文的话.

 

可以参考下面:

 

 将下面代码加入到你的获取上下文中

MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

会提示少jar.

 

把spring-mock.jar 加入即可

你可能感兴趣的:(用junit测试获取spring bean 报No Scope registered for scope 'session'错)