您的位置:首页 > 编程语言 > Java开发

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

2013-05-20 13:55 603 查看

spring 配置如下

 

 

<bean name="i18nManager" class="com.thams.service.I18nManager" scope="session">
<property name="messageSource" ref="messageSource" />
</bean>

 

 

测试类

 

@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 加入即可

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐