简体   繁体   English

在测试中模拟EJB注入

[英]Mocking EJB injection in tests

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? 是否存在另一种模拟资源注入的方法,或者这是正确的模式?

you could use easy gloss to that effect, it mocks the EJBs injection system. 你可以使用简单的光泽效果,它嘲笑EJB注入系统。

another way is to set the field using reflexion in your tests, I sometime use something like this : 另一种方法是在测试中使用reflexion设置字段,我有时会使用这样的东西:

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);
}

According to this article (Mockito and Dependency Injection) , Mockito has support for injecting mocked resources. 根据这篇文章(Mockito和Dependency Injection) ,Mockito支持注入模拟资源。

public class ATest
{
    @InjectMocks
    private A a; //this is your class under test into which the mocks will be injected.

    @Mock
    private B b; //this is the EJB to be injected.

    @Before
    public void setUp()
    {
        MockitoAnnotations.initMocks(this);
    }

}

You can also inject multiple mocks. 你也可以注入多个嘲笑。 Just declare them in the same way as we did for B b. 只需用与B b相同的方式声明它们。 The initMocks part can also be done in each test or in a BeforeClass setup method depending on your needs. initMocks部分也可以在每个测试中或在BeforeClass设置方法中完成,具体取决于您的需要。

Eliocs, Eliocs,

If type B where an interface then you wouldn't "just" bo doing it for test-cases; 如果键入B接口,那么你就不会“只是”为测试用例做这样的事情; you'd be allowing for any alternative implementations of "B's behaviour", even if the need for it/them hasn't been dreamed-up yet. 你会允许“B的行为”的任何替代实现,即使它/它们的需要尚未被设想。

Yeah, basically that's the only pattern to follow (AFAIK)... so (rightly or wrongly) you may as well make the best of it ;-) 是的,基本上这是唯一可以遵循的模式(AFAIK)......所以(正确或错误地)你也可以充分利用它;-)

Cheers. 干杯。 Keith. 基思。

It's certainly one way to do it, although I'd rely on package access; 这当然是一种方法,虽然我依赖于包访问; don't provide a constructor injection point, but simply have your test in the same package as the bean being tested. 不提供构造函数注入点,而只是将测试放在与被测试的bean相同的包中。 That way, your test can just access the value directly (assuming it's not private): 这样,您的测试可以直接访问该值(假设它不是私有的):

@Test
public void EJBInjectionTest() {
   A a=new A();
   a.b=new B() {
       // mock functionality here, of course...
   };
   assertNotNull(a.b);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM