0

So I have a session scoped bean and naturally, I'm getting the error you would expect in my unit tests.

java.lang.IllegalStateException: No Scope registered for scope 'Session'

What is the proper Java based way to mock a session for a unit test?

This was the old way:

Spring Test session scope bean using Junit

The thing is though that I don't need to test a controller. I'm testing a component with a session scoped bean in it. I just need a fake session so that it works.

Community
  • 1
  • 1
user447607
  • 5,149
  • 13
  • 33
  • 55
  • A unit test shouldn't need Spring at all. You create a mock bean, you create the component under test and pass it the mock bean as argument, and you call your method to test: `new ComponentUnderTest(mockedBean)` – JB Nizet Sep 17 '14 at 15:42
  • The problem is that there's a session scoped bean wired into the object under test. It's just a widget for registering something. – user447607 Sep 17 '14 at 15:49
  • So create a mock instance of this session scoped bean, and wire it manually in your bean under test. Also create the bean under test manually. You don't need Spring for a unit test. The whole idea of DI is to make unit tests easy. If you posted code, we could tell you how to fix it. – JB Nizet Sep 17 '14 at 16:12

1 Answers1

0

It was this easy :-/

In the test:

public void setup() throws Exception {
            ConfigurableBeanFactory factory = (ConfigurableBeanFactory) wac.getAutowireCapableBeanFactory();
            factory.registerScope("session", new SessionScope());
    }

Then you call that before every test that needs it. Could just use @Before if you are using JUnit.

user447607
  • 5,149
  • 13
  • 33
  • 55
  • Afterwards you have to annotate every class with @WebAppConfiguration. You also have to wire in a WebApplicationContext. That is what 'wac' is. – user447607 Sep 19 '14 at 21:00