Mockito: Mock class object

2019-07-23 05:42发布

问题:

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);