1

我有以下代码:

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吗?

4

1 回答 1

1

作为一种解决方法,它并不能真正解释任何事情(但有效且看起来合乎逻辑),我已将sleep()测试中的时间降低到 4500 毫秒。这样每次只发出 4 个事件。虽然不能解决正在发生的事情,所以如果有人能启发我,我会在这个线程中等待。

于 2017-11-14T21:12:35.747 回答