How can I mock methods of @InjectMocks class?

前端 未结 3 1358
慢半拍i
慢半拍i 2021-01-30 03:02

For example I have handler:

@Component
public class MyHandler {

  @AutoWired
  private MyDependency myDependency;

  public int someMethod() {
    ...
    retur         


        
3条回答
  •  感情败类
    2021-01-30 03:47

    All answers above are really good and may be useful so make sure you study and understand these principes first before continue reading my post.

    In my scenario none of advices above did not work. I will post what helped me after a pretty long debugging.

    If you want to call methods from tested class, the @Spy annotation is needed alongside @InjectMocks (or Mockito.spy(XXX) call or course)

    The interesting part is, the order of these annotations does matter! The @Spy annotation must precede @InjectMocks annotation.

    Will not work

    ...
    
    @InjectMocks
    @Spy
    private TestedObject instance
    
    ...
    

    Will work

    ...
    
    @Spy
    @InjectMocks
    private TestedObject instance
    
    ...
    

提交回复
热议问题