我有以下代码:
private AtomicInteger numberOfGeneratedEvents;
@Before
public void setNumberOfGeneratedEvents() {
numberOfGeneratedEvents = new AtomicInteger(0);
}
@Test
public void eventsShouldAppearDespiteException() {
ThreadFactory timerThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("timer-service-%d")
.build();
Observable<Long> timerService = Observable
.interval(1, 1, SECONDS)
.observeOn(Schedulers.from(Executors.newFixedThreadPool(1, timerThreadFactory)))
.doOnNext(aLong -> doSomeWork())
.doOnError(throwable -> doWorkAfterException())
.timeout(5, TimeUnit.SECONDS)
.retry();
timerService.subscribe();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
assertThat(numberOfGeneratedEvents.get()).isEqualTo(4);
}
private void doWorkAfterException() {
System.out.println("Exception happened. This code should do something onError. ");
}
private Boolean doSomeWork() {
numberOfGeneratedEvents.incrementAndGet();
System.out.println("Work work. ");
System.out.println("numberOfGeneratedEvents = " + numberOfGeneratedEvents.get());
if (Math.random() > 0.5) {
throw new NullPointerException("Random null pointer inside the work.");
}
return true;
}
转换为以下日志输出:
Work work.
numberOfGeneratedEvents = 1
Work work.
numberOfGeneratedEvents = 2
Work work.
numberOfGeneratedEvents = 3
Exception happened. This code should do something onError.
Work work.
numberOfGeneratedEvents = 4
Work work.
numberOfGeneratedEvents = 5
Exception happened. This code should do something onError.
Process finished with exit code 0
最让我担心且我不完全理解的是事实,即测试最后一行中的最后一个断言:
assertThat(numberOfGeneratedEvents.get()).isEqualTo(4);
实际上变成绿色并且测试通过了。另一次当我运行它时,我得到 4 作为控制台上的最后一个值,numberOfGeneratedEvents
并且测试也变为绿色,所以没关系。这里出了什么问题,随机性在哪里?我在做坏事AtomicInteger
吗?