Mockito @InjectMocks doesn't work for fields with same type

前端 未结 2 1462
陌清茗
陌清茗 2021-02-07 06:43

I was very surprised to find out that following simple code example doesn\'t work for all Mockito versions > 1.8.5

@RunWith(MockitoJUnitRunner.class)
public clas         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 07:40

    This is documented in mockito as work around, if multiple mocks exists of the same type. It does not resolve the implementation based on the name provided (ie @Mock(name = "b2")). The algorithm it uses to resolved the implementation is by field name of the injected dependency. So your code above will resolve correctly (b2 => @Mock private B b2 and b3 => @Mock private B b3).

    The other workaround is to use constructor injection which is the recommended way of injecting dependencies.

提交回复
热议问题