Mockito: Inject real objects into private @Autowired fields

后端 未结 5 2251
孤街浪徒
孤街浪徒 2020-11-29 17:56

I\'m using Mockito\'s @Mock and @InjectMocks annotations to inject dependencies into private fields which are annotated with Spring\'s @Autow

5条回答
  •  旧巷少年郎
    2020-11-29 18:26

    In Spring there is a dedicated utility called ReflectionTestUtils for this purpose. Take the specific instance and inject into the the field.

    
    @Spy
    ..
    @Mock
    ..
    
    @InjectMock
    Foo foo;
    
    @BeforeEach
    void _before(){
       ReflectionTestUtils.setField(foo,"bar", new BarImpl());// `bar` is private field
    }
    

提交回复
热议问题