在测试中模拟EJB注入 [英] Mocking EJB injection in tests

查看:135
本文介绍了在测试中模拟EJB注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我想测试一个使用资源注入的类时,我最终会包含一个仅在测试中使用的构造函数:

Whenever I want to test a class which uses resource injection I end up including a constructor that will only be used within the test:

public class A {

    @EJB
    B b;

    // Used in tests to inject EJB mock
    protected A(B b) {
        this.b = b;
    }

    public A() {}

    // Method that I wish to test
    public void foo() {
        b.bar();
    }

}

有另一种嘲笑资源的方法注入或这是正确的模式?

Is there another way of mocking resource injection or this is the correct pattern to follow?

推荐答案

你可以使用容易的光泽这样做,它嘲笑EJBs注入系统。

you could use easy gloss to that effect, it mocks the EJBs injection system.

另一种方法是设置字段在你的测试中使用反射,我有时使用这样的东西:

another way is to set the field using reflexion in your tests, I sometime use something like this :

public static void setPrivateField(Class<? extends Object> instanceFieldClass, Object instance, String fieldName, Object fieldValue) throws Exception {
    Field setId = instanceFieldClass.getDeclaredField(fieldName);
    setId.setAccessible(true);
    setId.set(instance, fieldValue);
}

这篇关于在测试中模拟EJB注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆