IllegalStateException:没有在单元测试中为范围'session'注册的Scope

dwj*_*ton 8 java spring-mvc junit4

我有一个mkyong MVC教程的修改版本.

我添加了一个业务层类Counter.

public class Counter {

    private int i;


    public int count()
    {
        return (this.i++);
    }

    //getters and setters and constructors
}
Run Code Online (Sandbox Code Playgroud)

在mvc-dispatcher-servlet.xml中:

<bean id="counter" class="com.mkyong.common.Counter" scope="session">
    <property name="i" value="0"></property>
</bean>
Run Code Online (Sandbox Code Playgroud)

这很好用.

我现在想为这个类创建一个单元测试

@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());

    }

}
Run Code Online (Sandbox Code Playgroud)

如果我像这样运行它,我会得到的

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
Run Code Online (Sandbox Code Playgroud)

所以我们需要指定上下文的位置:

@ContextConfiguration(locations="file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml")
Run Code Online (Sandbox Code Playgroud)

现在,如果我运行这个,我得到:

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'
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况,我该如何解决?

cod*_*ent 15

您只需要@WebAppConfiguration在测试类中添加以启用MVC范围(请求,会话......)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
@WebAppConfiguration
public class TestCounter {
Run Code Online (Sandbox Code Playgroud)