CurrencyConverterViewModel extends RxViewModel<Void, CurrencyConverterModel> { public void calculate() { String inputString = model.input.get(); try { final float input = Float.parseFloat(inputString); subscribe( new Action1<Boolean>() { @Override public void call(Boolean b) { loading.set(b); } }, rateLoader.loadRate(), new Action1<Float>() { @Override public void call(Float rate) { DecimalFormat decimalFormat = new DecimalFormat("0.00", DecimalFormatSymbols.getInstance(Locale.US)); model.output.set(decimalFormat.format(input * rate)); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { messageManager.showMessage(activityHolder, R.string.error_loading_rate); } }); } catch (NumberFormatException e) { messageManager.showMessage(activityHolder, R.string.conversion_error); } } CurrencyConverterViewModel(RateLoader rateLoader, MessageManager messageManager, SchedulerManager schedulerManager); @NonNull @Override CurrencyConverterModel createModel(); void calculate(); final ObservableBoolean loading; }
@Test public void testConvertCurrency() { when(rateLoader.loadRate()).thenReturn(Observable.just(2f)); CurrencyConverterModel model = viewModel.initAndResume(); model.input.set("123"); viewModel.calculate(); assertThat(model.output.get()).isEqualTo("246.00"); }
@Test public void testConvertCurrencyLoadingError() { when(rateLoader.loadRate()).thenReturn(Observable.<Float>error(new RuntimeException())); CurrencyConverterModel model = viewModel.initAndResume(); model.input.set("123"); viewModel.calculate(); verify(messageManager).showMessage(any(ActivityHolder.class), eq(R.string.error_loading_rate)); }
@Test public void testConvertCurrencyOnError() { when(rateLoader.loadRate()).thenReturn(Observable.just(2f)); CurrencyConverterModel model = viewModel.initAndResume(); model.input.set("abc"); viewModel.calculate(); verify(messageManager).showMessage(any(ActivityHolder.class), eq(R.string.conversion_error)); }