您好我有这样的代码: ```
abstract class AbstractBaseClass {
public String method() {
return "AbstractBaseClass.method";
}
}
public class ChildClass extends AbstractBaseClass {
public String start() {
}
}
@Test
public void test() {
ChildClass child = mock(ChildClass.class);
when(child.method()).thenReturn("my mock string");
System.out.println(child.method()); // AbstractBaseClass.method
}
``` 代码实际上运行父类方法而不是我的模拟方法。那么如何考虑它的抽象和非公共类来模拟父类。
答案 0 :(得分:0)
解决方案很简单:更新到较新版本的Mockito。这适用于mockito 2.7.22和Java 1.8。
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class Mockito {
abstract class AbstractBaseClass {
public String method() {
return "AbstractBaseClass.method";
}
}
public class ChildClass extends AbstractBaseClass {
public String start() {
return "";
}
}
@Test
public void test() {
ChildClass child = mock(ChildClass.class);
when(child.method()).thenReturn("my mock string");
assertThat(child.method(), is("my mock string")); // AbstractBaseClass.method
}
}