Mockito: Inject real objects into private @Autowired fields

后端 未结 5 2253
孤街浪徒
孤街浪徒 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:30

    In Addition to @Dev Blanked answer, if you want to use an existing bean that was created by Spring the code can be modified to:

    @RunWith(MockitoJUnitRunner.class)
    public class DemoTest {
    
        @Inject
        private ApplicationContext ctx;
    
        @Spy
        private SomeService service;
    
        @InjectMocks
        private Demo demo;
    
        @Before
        public void setUp(){
            service = ctx.getBean(SomeService.class);
        }
    
        /* ... */
    }
    

    This way you don't need to change your code (add another constructor) just to make the tests work.

提交回复
热议问题