我正在尝试为使用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();
}
}
确保在
getMapped1Table
和getMapped2Table
方法中最简单的方法是什么-我能够抛出InterruptedException
,以便我也能解决该情况。如果您查看这两种方法,那么我有一个无法解决的问题。MappedData.getMapped1Table()
有什么方法可以确保我上面的两种方法都抛出
InterruptedException
吗?更新:-
我正在尝试做的是-在我进行单元测试时如何获取firstSet.await()引发InterruptedException。
最佳答案
这是使用JMockit编写测试的最简单方法:
public class MappedDataTest
{
@Test
public void getMappedTableHandlesInterruptedException(
@Mocked final CountDownLatch anyLatch) throws Exception
{
final InterruptedException interrupt = new InterruptedException();
new NonStrictExpectations() {{ anyLatch.await(); result = interrupt; }};
try {
MappedData.getMapped1Table();
fail();
}
catch (IllegalStateException e) {
assertSame(interrupt, e.getCause());
}
}
}
关于java - 在junit测试我的类时如何抛出`InterruptedException`?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23093448/