大家好,我在创建模拟时遇到了麻烦。 这是代码:
我想要模拟的课程:
public class MyClass extends BaseClass<ClassView>{
//code goes here
}
在测试中:
MyClass mockMyClass;
@Test
public void setUp(){
mockMyClass = mock(MyClass.class);
}
也尝试过:
@Mock MyClass mockMyClass;
@Test
public void setUp(){
MockitoAnnotations.initMocks(this)
}
错误:
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class com.packageName.MyClass
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
我认为在为使用泛型参数扩展类的类创建模拟时存在问题。 有人能指出我正确的方向吗?
答案 0 :(得分:4)
您忘记了TestClass的两个强制性注释:
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClass.class})
public class FirstTest {
MyClass mockMyClass;
@Test
public void setUp(){
mockMyClass = mock(MyClass.class);
}
}
您的测试需要使用PowerMockRunner
执行,您还需要准备测试要模拟的所有类。如果你牢记这一点,它将工作正常:)