home ホーム search 検索 -  login ログイン  | reload edit datainfo version cmd icon diff delete  | help ヘルプ

日記/2010/10/14/System.exit(anyInt())をmockする!!

日記/2010/10/14/System.exit(anyInt())をmockする!!

日記 / 2010 / 10 / 14 / System.exit(anyInt())をmockする!!
id: 809 所有者: msakamoto-sf    作成日: 2010-10-14 12:35:56
カテゴリ: Java 
public class Foo {
    public void shutdown() {
        System.exit(0);
    }
}

Fooクラスのshutdown()メソッドで、以下の挙動をassertする!!

  1. System.exit()が呼ばれていること。
  2. その引数に"0"が渡されていること。

テストケース:

@RunWith(PowerMockRunner.class)
@PrepareForTest( { Foo.class })
public class FooTest extends TestCase {
 
    @Test
    public void shutdown()
    {
        PowerMockito.mockStatic(System.class);
 
        Foo f = new Foo();
        f.shutdown();
 
        PowerMockito.verifyStatic(Mockito.times(1));
        System.exit(0);
    }
}

これでOK。

色々試行錯誤したのだけど、"void"メソッドだからと

PowerMockito.doNothing().when(System.class);

してみたが、これ入れると以下のような例外が出てしまい、手詰まりに。

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:31)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. although stubbed methods may return mocks, you cannot inline mock creation (mock()) call 
  inside a thenReturn method (see issue 53)

外したら動いた。この辺が曖昧なのが多少気持ち悪いが、とりあえず前進を再開できる。

参考メモ:

Hotな話題だけに、トピック記事もsampleも出揃いつつあるのだけれど、中々"Spot On!"な回答/sampleが無くてやきもきした。


プレーンテキスト形式でダウンロード
現在のバージョン : 2
更新者: msakamoto-sf
更新日: 2010-10-14 13:06:24
md5:db8573b8fbc0a45462b3152cbff9d560
sha1:4fdc2ce11360e5589ddc1a63558b54cc2c0117ba
コメント
コメントを投稿するにはログインして下さい。