java—使用mockito为扩展泛型类的类创建mock

bihw5rsg  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(420)

嗨,伙计们,我很难创建一个模拟。代码如下:
我要嘲弄的班级:

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.

我认为在为一个用泛型参数扩展类的类创建mock时有一个问题。有人能给我指出正确的方向吗?

jckbn6z7

jckbn6z71#

您忘记了testclass的两个必需注解:

@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClass.class})
public class FirstTest {
    MyClass mockMyClass;

    @Test
    public void setUp(){
        mockMyClass = mock(MyClass.class);
    }
}

您的测试需要使用 PowerMockRunner 您还需要准备测试所有要模拟的类。如果你记住这一点,它会工作得很好:)

相关问题