Mockito 中的可选存根
我想在测试类的超类中创建一个方法,该方法在测试类中存根一些常用的方法,但其中一些方法可能不存在。
例如,我有一个像这样的类层次结构:
abstract class A {
void search(); // implemented by subclass
String getFoo() { return "REAL FOO"; }
}
class B extends A {
void search() {
getFoo();
}
}
class C extends A {
void search() {
getFoo();
getBar();
}
String getBar() { return "REAL BAR"; }
}
A 有大量的子类(生成骨架的工具),因此我想创建一个超类以方便我测试:
abstract class AbstractSearchTest {
A underTest;
@Test void test() {
doReturn( "FOO" ).when( underTest ).getFoo();
doReturn( "BAR" ).when( underTest, "getBar" ); // THE PROBLEM!
underTest.search();
}
}
class BSearchTest extends AbstractSearchTest {
BSearchTest() {
underTest = new B();
}
}
class CSearchTest extends AbstractSearchTest {
CSearchTest() {
underTest = new C();
}
}
这基本上是说,“在调用 search()
,存根 getFoo()
哦,如果子类碰巧有 getBar()
,也存根它。” 但我不能这样做,因为它会抛出org.powermock.reflect.exceptions.MethodNotFoundException。如何做到这一点?
I want to create a method in superclass of test-class that stubs some commonly used methods in under-test-classes but some of those methods might not exist.
For example, I have a class hierarchy like this:
abstract class A {
void search(); // implemented by subclass
String getFoo() { return "REAL FOO"; }
}
class B extends A {
void search() {
getFoo();
}
}
class C extends A {
void search() {
getFoo();
getBar();
}
String getBar() { return "REAL BAR"; }
}
There are tons of subclasses of A (a tool generated the skeleton) thus I want to create a superclass to make it easier for me to test:
abstract class AbstractSearchTest {
A underTest;
@Test void test() {
doReturn( "FOO" ).when( underTest ).getFoo();
doReturn( "BAR" ).when( underTest, "getBar" ); // THE PROBLEM!
underTest.search();
}
}
class BSearchTest extends AbstractSearchTest {
BSearchTest() {
underTest = new B();
}
}
class CSearchTest extends AbstractSearchTest {
CSearchTest() {
underTest = new C();
}
}
Which basically says, "Before invoking search()
, stub getFoo()
. Oh, if the subclass happen to have getBar()
, stub it too."
But I can't do that since it'll throw org.powermock.reflect.exceptions.MethodNotFoundException. How to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用反射来确定该类是否已实现。
Use reflection to determine if the class is implemented.