Java 模拟会话上下文

Java 模拟会话上下文,java,junit,dependency-injection,ejb-3.0,sessioncontext,Java,Junit,Dependency Injection,Ejb 3.0,Sessioncontext,我将SessionContext作为资源注入EJB(实现容器管理的事务): 我的单元测试失败,因为“sctx”在运行时为空(NullPointerException)。因此,我认为解决这个问题的唯一方法是创建一个FakeSessionContext类,该类实现SessionContext,然后我可以在测试期间使用它 instance = new Xxx(); sessionContextResourceField = Xxx.class.getDeclaredField("sctx"); ses

我将SessionContext作为资源注入EJB(实现容器管理的事务):

我的单元测试失败,因为“sctx”在运行时为空(NullPointerException)。因此,我认为解决这个问题的唯一方法是创建一个FakeSessionContext类,该类实现SessionContext,然后我可以在测试期间使用它

instance = new Xxx();
sessionContextResourceField = Xxx.class.getDeclaredField("sctx");
sessionContextResourceField.setAccessible(true);
sessionContextResourceField.set(instance, new FakeInitialContext());
但在我这么做之前,我想知道是否有更优雅的方式?除了创建FakeSessionContext类之外?像工厂级的


出于兴趣,我正在使用jUnit 4.10和jmockit 0.999.15。

使用jmockit为您创建会话上下文的模拟版本,并使用jmockit版本的“when…return”语句确保模拟上下文返回您需要的值。

为了其他人的利益,在jmockit中是这样做的:

sessionContextResourceField.set(instance, 
            new MockUp<SessionContext>() {
                @Mock boolean getRollbackOnly() { return false; }
            }.getMockInstance());
sessionContextResourceField.set(实例,
新模型(){
@模拟布尔getRollbackOnly(){return false;}
}.getMockInstance());

虽然在我的例子中,没有必要只模拟GetRollback(我在代码中使用了它),但我还是这样做了,以防将来行为发生变化。

是的。使用你的模拟框架,让它为你创建一个假的会话上下文。
sessionContextResourceField.set(instance, 
            new MockUp<SessionContext>() {
                @Mock boolean getRollbackOnly() { return false; }
            }.getMockInstance());