[英]Optional stubbing in Mockito
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. 我想在test-class的超类中创建一个方法,它在欠测试类中存根一些常用的方法,但是其中一些方法可能不存在。
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: 有很多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();
}
}
Which basically says, "Before invoking search()
, stub getFoo()
. Oh, if the subclass happen to have getBar()
, stub it too." 其中基本上说,“在调用
search()
之前,存根getFoo()
。哦,如果子类碰巧有getBar()
,那么也存根。” But I can't do that since it'll throw org.powermock.reflect.exceptions.MethodNotFoundException . 但我不能这样做,因为它会抛出org.powermock.reflect.exceptions.MethodNotFoundException 。 How to do this?
这个怎么做?
Use reflection to determine if the class is implemented. 使用反射来确定是否实现了类。
try{
Method m = underTest.getClass().getMethod("getBar");
// no exception means the method is implememented
// Do your mocking here
doReturn( "BAR" ).when( underTest, "getBar" );
}catch(NoSuchMethodException e){}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.