Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 998
eliocs Avatar asked Nov 14 '22 00:11

eliocs


1 Answers

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);
}
like image 183
user691154 Avatar answered Dec 15 '22 01:12

user691154