如何模拟超级方法(带返回)

时间:2013-01-23 17:29:41

标签: java junit mockito easymock jmockit

是否可以模拟超类的方法? (没有改写)

public class FooBarTest {

    @Test
    public void test() {
        Bar bar = Mockito.spy(new Bar());
        Mockito.doReturn("Mock!").when((Foo) bar).test();

        String actual = bar.test(); // returns only "Mock!"
        assertEquals("Mock! Bar!", actual);
    }

    public static class Foo {
        public String test(){
            return "Foo!";
        }
    }

    public static class Bar extends Foo {
        @Override
        public String test(){
            return super.test()+" Bar!";
        }
    }
}

关闭:如何突出显示代码?

1 个答案:

答案 0 :(得分:1)

这是一个使用JMockit模拟API的解决方案:

public class FooBarTest
{
    @Test
    public void test()
    {
        final Bar bar = new Bar();
        new NonStrictExpectations(Foo.class) {{ bar.test(); result = "Mock!"; }};

        String actual = bar.test();
        assertEquals("Mock! Bar!", actual);
    }

    public static class Foo {
        public String test() { return "Foo!"; }
    }

    public static class Bar extends Foo {
        @Override
        public String test() { return super.test() + " Bar!"; }
    }
}