Injection of a mock object into an object to be tested declared as a field in the test does not work using Mockito?

前端 未结 2 1890
春和景丽
春和景丽 2021-01-01 02:30

I have a class and I am injecting a proxy into my service.

Service service
{
    private ServiceProxy proxy;
    public Service(ServiceProxy proxy)
    {
           


        
相关标签:
2条回答
  • 2021-01-01 02:49

    Write your test class as this, which will initialize Service with a mock of ServiceProxy:

    class ServiceTest
    {
    @Mock
    ServiceProxy mockProxy;
    
    //This will inject the "ServiceProxy" mock into your "Service" instance.
    @InjectMocks
    Service service = new Service(mockProxy);
    
    @Before
    public void init() {
    //This will initialize the annotated mocks 
    MockitoAnnotations.initMocks(this);
    }
    
    @Test
    public void test() {
    ... 
    }
    }
    
    0 讨论(0)
  • 2021-01-01 02:55

    Provided you are using Mockito version 1.9.0 or later, the best way to achieve what you want is like this:

    @RunWith(MockitoJUnitRunner.class)
    public class ServiceTest {
    
        @Mock
        private ServiceProxy proxy;
    
        @InjectMocks
        private Service service;
    
        @Test
        public void test() {
            assertNotNull(service);
            assertNotNull(proxy);
        }
    }
    

    First thing is the @RunWith(MockitoJUnitRunner.class) declaration which will cause @Mock and @InjectMocks annotation to work automatically without any explicit initialization. The second thing is that starting with Mockito 1.9.0 @InjectMocks annotation can use the Constructor injection mechanism which is the best option for your Service class.

    Other options for @InjectMocks are Setter injection and Field injection (see docs BTW) but you'd need a no argument constructor to use them.

    So summarizing - your code cannot work because:

    • you are not using the MockitoJUnitRunner nor MockitoAnnotations.initMocks(this) so @Mock annotation takes no effect
    • even if above were satisfied your example would fail because mockProxy would be initialized after the test is constructed and your service is tried to be initialized during the test class construction, hence it receives null mockProxy reference.

    If for some reason you don't want to use @InjectMocks, the only way is to construct your Service object within the test method body or within the @Before annotated setUp method.

    0 讨论(0)
提交回复
热议问题