Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a modified version of the mkyong MVC tutorial.

I've added a business layer class Counter.

public class Counter {

    private int i;


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

    //getters and setters and constructors
}

In mvc-dispatcher-servlet.xml:

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

This works fine.

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?

like image 211
dwjohnston Avatar asked Apr 15 '15 03:04

dwjohnston


1 Answers

You just need to add @WebAppConfiguration in your test class to enable MVC scopes (request, session...)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
@WebAppConfiguration
public class TestCounter {
like image 54
codependent Avatar answered Nov 15 '22 22:11

codependent