模拟的ReactiveX流和Singles不发出元素

时间:2018-07-13 11:14:55

标签: unit-testing junit mockito rx-java reactivex

我正在使用Mockito模拟对象来测试基于RxJava的某些功能。我有一个地方需要模拟返回值Single<HttpResponse<Buffer>>的值,但是当我这样做时,Single不会发出任何元素。我在调试器中检查了值,它似乎是同一对象(一个对象在开头模拟,另一个对象从应该发出值的方法返回)。但这并没有达到预期效果,我的流结束为空。

这是我的模拟和返回规则:

WebClient webClient = mock(WebClient.class);
HttpRequest<Buffer> httpRequest = mock(HttpRequest.class);
HttpResponse<Buffer> httpResponse = mock(HttpResponse.class);

when(httpResponse.statusCode()).thenReturn(200);
when(httpResponse.bodyAsString()).thenReturn(String.format("{\"%s\" : \"%s\"}", "address", testAddress));
when(httpRequest.addQueryParam(any(), any())).thenReturn(httpRequest);
when(httpRequest.rxSend()).thenReturn(Single.just(httpResponse)); // this returned Single doesn't emit the value
when(webClient.post(any())).thenReturn(httpRequest);

其他模拟对象可以正确返回,它们是webClienthttpRequesthttpResponse。我正在谈论的Single也可以正确返回(它在value字段中包含一个模拟对象,我在调试器中检查了该对象),但是它不会发出。

发射应该在这里发生

@Override
public Single<String> registerUserWallet(String userHash) {

    Single<HttpResponse<Buffer>> test = httpClient.post(EthereumApiEndpoints.MANAGED_ACCOUNT.uri)
            .addQueryParam("path", userHash)
            .rxSend();

    return test
            .doOnSubscribe(() -> log.debug("debug")) // none of this logs are printed out
            .doOnEach(x -> log.debug("debug"))
            .doOnError(x -> log.debug("debug"))
            .doOnSuccess(x -> log.debug("debug"))
            .flatMap(this::handleResponse);
}

我创建了test变量以在调试器中检查其值。每个对象都在适当的位置,httpRequest和httpResponse work well, the problem is with emission of Single>测试`。

编辑:使用Single的方法:

private Observable<AbstractMap.SimpleEntry<UserWallet, String>> mapWalletWithAddress(UserWallet wallet) {

        return userWalletDao.findFirstRegisteredWalletsForUserInNetwork(wallet.getUserId(),
                blockchainIntegration.getNetwork())
                .map(UserWallet::getAddress)
                .doOnNext(alreadyRegisteredAddress -> log.info("Found already registered address for user " +
                        "{} in {} network", wallet.getUserId(), blockchainIntegration.getNetwork()))
                .onErrorResumeNext(blockchainIntegration.registerUserWallet(wallet.getUserId()).toObservable()
                        .doOnNext(generatedAddress -> log.info("Generated new address {} for user {}.",
                                generatedAddress, wallet.getUserId())))
                .map(walletAddress -> new AbstractMap.SimpleEntry<>(wallet, walletAddress))
                .doOnNext(walletAddressPair -> log.info("Mapped wallet {} with address {}.",
                        walletAddressPair.getKey(), walletAddressPair.getValue()));
    }
}

我试图在数小时内找出问题所在。我希望你们能很快找到它。

0 个答案:

没有答案