Mocking EJB injection in tests

后端 未结 4 1293
盖世英雄少女心
盖世英雄少女心 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.

提交回复
热议问题