我有以下Java代码用于重试特定操作
package helpers;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public final class Retry {
public static <V> V execute(Callable<V> action, Duration retryInterval, int retryCount)
throws AggregateException {
List<Throwable> exceptions = new ArrayList<>();
for (int retry = 0; retry < retryCount; ++retry) {
try {
if (retry > 0)
Thread.sleep(retryInterval.toMillis());
return action.call();
} catch (Throwable t) {
exceptions.add(t);
}
}
throw new AggregateException(exceptions);
}
public static <V> Future executeAsync(Callable<V> action, Duration retryInterval, int retryCount)
throws AggregateException {
FutureTask<V> task = new FutureTask<>(action);
ExecutorService executor = Executors.newSingleThreadExecutor();
return executor.submit(task);
}
}
我正在尝试通过
测试同步代码的功能package helpers;
import org.junit.Before;
import org.junit.Test;
import java.text.MessageFormat;
import java.time.Duration;
import java.util.concurrent.Callable;
import static org.junit.Assert.assertEquals;
public class RetryTest {
private Integer counter = 0;
private Callable<Integer> calculator;
@Before
public void init() {
calculator = () -> {
for (int i = 0; i < 3; ++i) {
counter++;
System.out.println(MessageFormat.format(
"Counter = {0}", Integer.toString(counter)));
}
if (counter < 6)
throw new Exception();
return counter;
};
}
@Test
public void execute() throws AggregateException {
Integer result = Retry.execute(calculator, Duration.ofSeconds(1), 3);
assertEquals(9, java.util.Optional.ofNullable(result));
}
}
但是calculator
中的Retry.execute(calculator, Duration.ofSeconds(1), 3);
为空,为什么和我在这里做错什么?
我正在使用Junit 4.12。
我也尝试了完整的语法
@Before
public void init() {
calculator = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
for (int i = 0; i < 3; ++i) {
counter++;
System.out.println(MessageFormat.format(
"Counter = {0}", Integer.toString(counter)));
}
if (counter < 6)
throw new Exception();
return counter;
}
};
}
仍然为空。
答案 0 :(得分:2)
我使用JUnit 3
测试过,并且从未调用过@Before
。然后,我使用JUnit 4进行了测试,并调用了@Before
,尝试查看您的JUnit版本。
答案 1 :(得分:1)
您可以检查此测试代码吗?
node3