Mockito: Mock class<T> object

孤者浪人 提交于 2019-12-10 23:07:48

问题


Apologies if it's already been discussed but I didn't find any solutions.

Problem - Trying to mock an object of my Class of some type (e.g. class)

Writing test case of method xyz() where i need to mock SomeClass.class as mentioned in below code snippets

void xyz() {
..
MyOtherClass.staticMethod(SomeClass.class);
..
}

MyOtherClass {
..
<T> T staticMethod(Class<T> clazz) {
}
...
}
  1. Using power mockito
  2. Tried (Class) Mockito.mock(Class.class), which is not working.

I hope above code clears the problem. Any help much appreciated.

Thanks a ton!


回答1:


Yup, found solutions:

Run your test case with PowerMockRunner by annotating as follow:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ MyOtherClass.class, MainClass.class})

Mock your static method and supply expected object of your class of specific type:

PowerMockito.mockStatic(MyOtherClass.class);
PowerMockito.when(MyOtherClass.staticMethod((Class<SomeClass>) SomeClass.class)).thenReturn(...);

Thanks




回答2:


Try Mockito.mock(Class<T>.class);



来源:https://stackoverflow.com/questions/31943176/mockito-mock-classt-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!