计算事件并测试rxJava

时间:2017-11-14 14:09:32

标签: java unit-testing rx-java assertj

我有以下代码:

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做错了吗?

1 个答案:

答案 0 :(得分:1)

作为一种解决方法,它并没有真正解释任何事情(但是工作和看起来合乎逻辑)我已经将测试中的server { listen 443 ssl; server_name olddomain.com; ssl on; ssl_certificate /etc/ssl/certs/OLD.crt; ssl_certificate_key /etc/ssl/private/OLD.key; #enables all versions of TLS, but not SSLv2 or 3 which are weak and now deprecated. ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers "ALLLLLLTTHHISSSS"; ssl_prefer_server_ciphers on; rewrite 301 https://newdomain.com$request_uri; } 降低到4500毫秒。这样每次只发出4个事件。 虽然没有解决发生的事情,所以如果有人能够点燃我,我会在这个帖子中等待。