3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【誤りでした】EasyMockでfinalメソッドをモック化

Last updated at Posted at 2014-02-13

できたと思ってたのはEasyMockをうまく騙せて、Partial Mockインスタンスを作成できたというだけでした。デバッグしてみると実際のfinalメソッドが呼ばれてしまうのでダメでした。誤解を与える記事を書いてしまい、すみませんでした。

ネタ感満載。
finalメソッドをモック化したい場合。PowerMock使えないけどなんとかしたいとかそんなときに。

Sample.java
public void hoge() {
    finalMethod();
}

public final void finalMethod() {
    // do something
}

final修飾子をなかったことにすればいい。

SampleTest.java
public class SampleTest extends EasyMockSupport {
    private Sample testee;
    @Test
    public void testHoge() throws Exception {
        Method finalMethod = Sample.class.getMethod("finalMethod");
        Field modifiers = finalMethod.getClass().getDeclaredField("modifiers");
        modifiers.setAccessible(true);
        modifiers.set(finalMethod, Modifier.PUBLIC.ordinal());
        modifiers.setAccessile(false);
        testee = createMockBuilder(Sample.class).addMockedMethod(finalMethod).createMock();
        testee.finalMethod();
        replayAll();
        testee.hoge();
        verifyAll();
    }
}

FW開発ならまだしも、通常のアプリ開発でfinalって見ないなー。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?