Search code examples
sessionjunitglassfishejbcdi

CDI SessionScoped POJO inside an in-container JUnit test


I'm testing a web application using JUnit. The buisness layer of this application is writed in EJB stateless classes. So I do "in container" tests with JUnit and Glassfish-embedded. All works fine so far, EJBs are injected using lookup functions. Here are a simple test case :

public class SupportTest {

private static EJBContainer container;

private static MyEJB myEjb;

@BeforeClass
public static void setUpServices() throws NamingException {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(EJBContainer.MODULES, new File("target/classes"));
    container = EJBContainer.createEJBContainer(properties);
    myEjb = (MyEJB) container.getContext().lookup("java:global/classes/MyEJB");
}

@Test
public void test() {
    myEjb.doSomething("user_login");
}

}

Now I have a SessionScoped POJO (CDI) which keep information such as user login and so on. This Pojo is injected inside a static class. Like this :

public class MyStaticClass {

public static boolean verifyLogin(String login) {
    MySessionPojo mySessionPojo = CDI.current().select(MySessionPojo.class).get();
    return mySessionPojo.getLogin().equals(login);
}

}

This static class is used in EJB to secure the buisness code, like this :

@Stateless
public class MyEJB {

public void doSomething(String login) {
    if(MyStaticClass.verifyLogin(login)){
        //do something
    }
}
}

Inside a normal Glassfish 4.1 server, the injection of the POJO inside the static class works fine. Inside the Glassfish-embedded, the POJO injection fails with this message :

WELD-001303: No active contexts for scope type javax.enterprise.context.SessionScoped

I assume this is because there is no Http Session bound to it. Is there a way to simulate/create à SessionContext programmatically?

Thanks.


Solution

  • Ok, I finally find a workaround. I use the framework JMockit to replace the static class by a mock class, with fake methods which always return TRUE. (I had already tested Mockito and PowerMock, but both didn't work).