BAEL-4126

This commit is contained in:
kaushal 2021-06-05 13:25:29 +05:30
parent 559d47a612
commit 0c11282243
2 changed files with 89 additions and 0 deletions

View File

@ -32,6 +32,12 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>

View File

@ -1,10 +1,12 @@
package com.baeldung.mono;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.awt.image.SampleModel;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
@ -13,6 +15,7 @@ import java.util.Optional;
import static org.junit.Assert.assertEquals;
@Slf4j
public class MonoUnitTest {
@Test
public void whenMonoProducesString_thenBlockAndConsume() {
@ -80,4 +83,84 @@ public class MonoUnitTest {
return Mono.just(list);
}
@Test
public void whenEmptyList_thenMonoDeferExecuted() {
Mono<List<String>> emptyList = Mono.defer(() -> monoOfEmptyList());
//Empty list, hence Mono publisher in switchIfEmpty executed after condition evaluation
Flux<String> emptyListElements = emptyList.flatMapIterable(l -> l)
.switchIfEmpty(Mono.defer(() -> sampleMsg("EmptyList")))
.log();
StepVerifier.create(emptyListElements)
.expectNext("EmptyList")
.verifyComplete();
}
@Test
public void whenNonEmptyList_thenMonoDeferNotExecuted() {
Mono<List<String>> nonEmptyist = Mono.defer(() -> monoOfList());
//Non empty list, hence Mono publisher in switchIfEmpty won't evaluated.
Flux<String> listElements = nonEmptyist.flatMapIterable(l -> l)
.switchIfEmpty(Mono.defer(() -> sampleMsg("NonEmptyList")))
.log();
StepVerifier.create(listElements)
.expectNext("one", "two", "three", "four")
.verifyComplete();
}
private Mono<List<String>> monoOfEmptyList() {
List<String> list = new ArrayList<>();
return Mono.just(list);
}
@Test
public void whenUsingMonoJust_thenEagerEvaluation() throws InterruptedException {
Mono<String> msg = sampleMsg("Eager Publisher");
log.debug("Intermediate Test Message....");
StepVerifier.create(msg)
.expectNext("Eager Publisher")
.verifyComplete();
Thread.sleep(5000);
StepVerifier.create(msg)
.expectNext("Eager Publisher")
.verifyComplete();
}
@Test
public void whenUsingMonoDefer_thenLazyEvaluation() throws InterruptedException {
Mono<String> deferMsg = Mono.defer(() -> sampleMsg("Lazy Publisher"));
log.debug("Intermediate Test Message....");
StepVerifier.create(deferMsg)
.expectNext("Lazy Publisher")
.verifyComplete();
Thread.sleep(5000);
StepVerifier.create(deferMsg)
.expectNext("Lazy Publisher")
.verifyComplete();
}
private Mono<String> sampleMsg(String str) {
log.debug("Call to Retrieve Sample Message!! --> {} at: {}", str, System.currentTimeMillis());
return Mono.just(str);
}
}