开发者

Optional stubbing in Mockito

开发者 https://www.devze.com 2023-04-07 05:15 出处:网络
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.

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 {
    vo开发者_JS百科id 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?


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){}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号