2

I'm injecting SessionContext as a resource to an EJB (implementing container managed transactions):

@Stateless(name = "XXX", mappedName = "PPP-MMM-CCC")
@TransactionManagement(value=TransactionManagementType.CONTAINER)
public class Xxx implements ItsRemoteInterface {
   @Resource
   private SessionContext sctx;
   ....
}

My unit tests are failing because "sctx" is null while they're running (NullPointerException). So the only way I've figured to fix this is to create a FakeSessionContext class that implements SessionContext which then I can use during the test.

instance = new Xxx();
sessionContextResourceField = Xxx.class.getDeclaredField("sctx");
sessionContextResourceField.setAccessible(true);
sessionContextResourceField.set(instance, new FakeInitialContext());

But before I do that, I was wondering if there is a more elegant way? Other than creating a FakeSessionContext class? Something like a factory class?

In case of interest, I'm using jUnit 4.10 and jmockit 0.999.15.

Rob
  • 4,927
  • 12
  • 49
  • 54
Amir Keibi
  • 1,991
  • 28
  • 45

2 Answers2

1

Use jmockit to create a mock version of the session context for you, and use jmockit's version of "when... return" statements to ensure the mock context returns the values you need it to.

TrueDub
  • 5,000
  • 1
  • 27
  • 33
0

for the benefit of others, this is how it's done in jmockit:

sessionContextResourceField.set(instance, 
            new MockUp<SessionContext>() {
                @Mock boolean getRollbackOnly() { return false; }
            }.getMockInstance());

Although in my case it wasn't necessary to Mock getRollbackOnly (which I use in the code) I did it anyway in case in future the behaviour changes.

Amir Keibi
  • 1,991
  • 28
  • 45