Mockito - spying on real objects calls original method

后端 未结 2 905
情书的邮戳
情书的邮戳 2021-02-18 20:32

Imagine following code:

List list = .....
List spy = spy(list);
doThrow(new NullpointerException()).when(spy).get(0);

doThrow(....)

2条回答
  •  感情败类
    2021-02-18 21:12

    Mockito.doThrow(new NullpointerException()).when(spy).get(0);
    

    I think the problem here is that you are trying to do a partial mock and so you have to have the annotation on your test class:

    @PrepareForTest(List.class)
    

    This may or may not work. Looking at my code where I test exception handling, I always have done it on a fully-mocked object, not a partially mocked one. Also, I have made extensive use of PowerMockito when partial mocking, so it is possible that library will do what you need.

提交回复
热议问题