本文介绍了IllegalStateException:没有在单元测试中为作用域“会话"注册作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我添加了业务层类Counter
.
public class Counter {
private int i;
public int count()
{
return (this.i++);
}
//getters and setters and constructors
}
在mvc-dispatcher-servlet.xml中:
In mvc-dispatcher-servlet.xml:
<bean id="counter" class="com.mkyong.common.Counter" scope="session">
<property name="i" value="0"></property>
</bean>
这很好.
我现在想为此课程创建一个单元测试
I now want to create a unit test for this class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class TestCounter {
@Configuration
static class TestConfig
{
@Bean
public Counter c()
{
return new Counter();
}
}
@Autowired
private Counter c;
@Test
public void count_from1_returns2()
{
c.setI(1);
assertEquals(2, c.count());
}
}
如果我这样运行,我会得到
If I run it like this, I'll get
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@655bf451] to prepare test instance [com.mkyong.common.TestCounter@780525d3]
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [com/mkyong/common/TestCounter-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [com/mkyong/common/TestCounter-context.xml] cannot be opened because it does not exist
所以我们需要指定上下文在哪里:
So we need to specify where our context is:
@ContextConfiguration(locations="file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml")
现在,如果运行此命令,我将得到:
Now if I run this I get:
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5a2611a6] to prepare test instance [com.mkyong.common.TestCounter@7950d786]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mkyong.common.TestCounter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mkyong.common.Counter com.mkyong.common.TestCounter.c; nested exception is java.lang.IllegalStateException: No Scope registered for scope 'session'
为什么会这样,怎么解决?
Why is this happening, and how do I resolve it?
推荐答案
您只需要在测试类中添加@WebAppConfiguration
即可启用MVC范围(请求,会话...)
You just need to add @WebAppConfiguration
in your test class to enable MVC scopes (request, session...)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
@WebAppConfiguration
public class TestCounter {
这篇关于IllegalStateException:没有在单元测试中为作用域“会话"注册作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!