Reputation: 7980
I am trying to write test cases for a function which return some data if validation passes else throws exception
private String validate(Test test) {
//Validation Logic which returns null or throws Exception
}
public Observable<Test> create(Test test) {
return Observable
.just(validate(test))
.flatMap(x -> testRepository
.create(test));
}
Test case for the same
@Test
public void Should_ThrowException_When_NoData() {
Test test = sampleTest();
TestSubscriber<Test> subscriber = new TestSubscriber<>();
testService
.create(test)
.subscribe(subscriber);
subscriber.awaitTerminalEvent();
Throwable thrown = subscriber.getOnErrorEvents().get(0);
assertThat(thrown)
.isInstanceOf(CustomException.class)
.hasFieldOrPropertyWithValue("errorId", 102);
}
But the test case is failing on testService.create itself.
What is the problem here?
Thanks
Upvotes: 0
Views: 625
Reputation: 69997
It fails because you call validate()
before its return value is used for creating the Observable. Instead, you can call fromCallable(() -> validate(test))
and get the execution of validate
deferred.
Upvotes: 2