gpt4 book ai didi

unit-testing - 单元测试 RxJava doOnSubscribe 和 doFinally

转载 作者:行者123 更新时间:2023-11-28 20:37:29 27 4
gpt4 key购买 nike

我如何创建一个单元测试,以在 rxjava 链的 doOnScubscribedoFinally 上完成某种副作用?

例如:

Observable.requestSomeValueFromWeb()
.doOnSubscribe(() -> showLoading = true)
.doFinally(() -> showLoading = false)
.subscribe(result -> doSomething(result), error -> doErrorHandling(error));

我如何在上面的场景中测试 showLoading 在订阅时设置为 true 而在处理 observable 时设置为 false?

TestSubscriber<WebServiceResponse> loginRequestSubscriber = new TestSubscriber<>();

clientLoginViewModel.requestLogin().subscribe(loginRequestSubscriber);

// check that showLoading was true when webservice was called
assertEquals(true, showLoading);

// check that showLoading was false when webservice was finished
assertEquals(false, showLoading);

loginRequestSubscriber.assertSubscribed();

最佳答案

If I understand correctly, your Object Under Test is the ClientLoginViewModel, so I'm trying to work from there. Let me know if I'm mistaken and I can revisit my answer:

您系统中的类:

interface WebServiceResponse { } // We don't care about this here

interface Network {
// This is whatever interacts with the Network, and we'll mock it out
Single<WebServiceResponse> requestSomeValue();
}

// The class we are testing
class ClientLoginViewModel {

final Network mNetwork;

// This is the field we want to check... you probably want to make it
// private and have accessors for it
boolean showLoading;

// This allows dependency injection, so we can mock :)
ClientLoginViewModel(final Network network) {
mNetwork = network;
}

// The actual method to test!
Single<WebServiceResponse> requestLogin() {
return mNetwork.requestSomeValue()
.doOnSubscribe(disposable -> showLoading = true)
.doFinally(() -> showLoading = false);
}
}

现在是测试!!!

class ClientLoginViewModelTest {

@Test
public void testLoading() {
final Network network = mock(Network.class);
final WebServiceResponse response = mock(WebServiceResponse.class);

// This is the trick! We'll use it to allow us to assert anything
// before the stream is done
final PublishSubject<Boolean> delayer = PublishSubject.create();
when(network.requestSomeValue())
.thenReturn(

Single.just(response).delaySubscription(publishSubject)
);

final ClientLoginViewModel clientLoginViewModel = new ClientLoginViewModel(network);

clientLoginViewModel
.requestLogin()
.test();

// check that showLoading was true when webservice was called
assertEquals(true, clientLoginViewModel.showLoading);

// now let the response from the Network continue
publishSubject.onComplete();

// check that showLoading was false when webservice was finished
assertEquals(false, clientLoginViewModel.showLoading);
}
}

关于unit-testing - 单元测试 RxJava doOnSubscribe 和 doFinally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48980897/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com