2

スーパークラスのメソッドのモックを作ることは可能ですか? (上書きされません)

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!";
        }
    }
}

オフ: ここでコードを強調表示するには?

4

1 に答える 1

1

JMockitモックAPIを使用した1つの解決策は次のとおりです。

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!"; }
    }
}
于 2013-01-29T11:10:41.137 に答える