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

IllegalStateException: No Scope registered for scope 'session' on unit test

我有修改版的mkyong MVC tutorial.

我添加了业务层classCounter

public class Counter {

    private int i;


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

    //getters and setters and constructors
}

在 mvc-dispatcher-servlet.xml:

<bean id="counter" class="com.mkyong.common.Counter" scope="session">
    <property name="i" value="0"></property>
</bean>

这很好用。

我现在想为此创建一个单元测试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());

    }

}

如果我运行这样,我会得到

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

所以我们需要指定我们的上下文在哪里:

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

现在如果我 运行 我得到:

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'

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

您只需在测试中添加 @WebAppConfiguration class 即可启用 MVC 作用域(请求、会话...)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
@WebAppConfiguration
public class TestCounter {