EJB eruption in tests

Whenever I want to test a class that uses resource injection, I end up with a constructor that will only be used in 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 to mock resources, or is this the right pattern?

+5
source share
4 answers

you can use light shine , it mocks the EJB injection system.

Another way is to set the field using reflection in your tests, I will someday 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);
}
+1
source

Eliocs,

B, , "" ; " B", / .

, , , (AFAIK)... ( ), , -)

. .

0

, , ; , , bean. , ( ):

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

According to this article (Mockito and Dependency Injection) , Mockito has support for injecting fake resources.

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 enter several layouts. Just declare them the same way we did for B b. The initMocks part can also be executed in each test or in the BeforeClass installation method, depending on your needs.

0
source

All Articles