2

CountDownLatch を使用しているクラス用の junit を作成しようとしていますが、jmockit ライブラリを使用して junit テストを行っています。

public class MappedData {

    private static final AtomicReference<Map<String, Map<Integer, String>>> mapped1 = new AtomicReference<Map<String, Map<Integer, String>>>();
    private static final AtomicReference<Map<String, Map<Integer, String>>> mapped2 = new AtomicReference<Map<String, Map<Integer, String>>>();
    private static final CountDownLatch firstSet = new CountDownLatch(1);

    public static Map<String, Map<Integer, String>> getMapped1Table() {
    try {
        firstSet.await();
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return mapped1.get();
    }

    public static Map<String, Map<Integer, String>> getMapped2Table() {
    try {
        firstSet.await();
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return mapped2.get();
    }
}

getMapped1Tableandメソッドでそれを確認する最も簡単な方法は何ですか-そのシナリオもカバーできるgetMapped2Tableようにをスローできます。InterruptedExceptionこれらの 2 つの方法を調べると、カバーできない catch ブロックがあります。

MappedData.getMapped1Table()

上記の2つのメソッドがスローされていることを確認する方法はありInterruptedExceptionますか?

アップデート:-

私がやろうとしているのは、junit テスト中に firstSet.await() を取得して InterruptedException をスローする方法です。

4

3 に答える 3

1

別のスレッドでメソッドを呼び出してから、そのスレッドを中断します。

Thread t = new Thread(new Runnable(){
   public void run(){
      MappedData.getMappedTable();
    }
});

t.start();

t.interrupt();
于 2014-04-15T21:26:42.270 に答える
0

MockitoEasyMockなどのモッキング ライブラリを使用して実行できます。モック依存関係を注入する方法が必要になります。通常、これはコンストラクターを介して行われますが、フィールドが であるため、staticおそらくセッターを追加する必要があります。

public static void setFirstSet(CountDownLatch latch)
{
    firstSet = latch;
}

この例の残りの部分は Mockito 用です。

テストで、モックを作成しますCountDownLatch

CountDownLatch mockLatch = mock(CountDownLatch.class);

次に、メソッドをスタブして例外をスローします。

when(mockLatch.await()).thenThrow(new InterruptedException());

次にモックを挿入します。

MappedData.setFirstSet(mockLatch);

最後に、テスト対象のメソッドを呼び出します。

Map<String, Map<Integer, String>> result = MappedData.getMapped1Table();

私はjmockitを使用したことがありませんが、簡単なグーグル検索から、これがそれを行う方法であることが示唆されています:

final CountDownLatch mockLatch = new CountDownLatch();
new Expectations(mockLatch){
    {
        mockLatch.await();
        result = new InterruptedException();
    }
};
MappedData.setFirstSet(mockLatch);
Map<String, Map<Integer, String>> result = MappedData.getMapped1Table();
于 2014-04-15T20:24:32.870 に答える