Mocking EJB injection in tests

后端 未结 4 1258
盖世英雄少女心
盖世英雄少女心 2021-01-13 03:25

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 {

             


        
相关标签:
4条回答
  • 2021-01-13 04:01

    According to this article (Mockito and Dependency Injection), Mockito has support for injecting mocked 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 inject multiple mocks. Just declare them in the same way as we did for B b. The initMocks part can also be done in each test or in a BeforeClass setup method depending on your needs.

    0 讨论(0)
  • 2021-01-13 04:04

    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. 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);
    }
    
    0 讨论(0)
  • 2021-01-13 04:09

    Eliocs,

    If type B where an interface then you wouldn't "just" bo doing it for test-cases; 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.

    Yeah, basically that's the only pattern to follow (AFAIK)... so (rightly or wrongly) you may as well make the best of it ;-)

    Cheers. Keith.

    0 讨论(0)
  • 2021-01-13 04:13

    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);
    }
    
    0 讨论(0)
提交回复
热议问题