|
| 1 | +package com.baeldung.mono |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Assertions |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | +import reactor.core.publisher.Mono |
| 6 | +import reactor.test.StepVerifier |
| 7 | +import java.util.concurrent.atomic.AtomicInteger |
| 8 | + |
| 9 | +class MonoUnitTest { |
| 10 | + |
| 11 | + @Test |
| 12 | + fun `mapping function is skipped for empty Mono`() { |
| 13 | + val callCount = AtomicInteger(0) |
| 14 | + val emptyMono = Mono.empty<String>() |
| 15 | + val resultMono = emptyMono.map { |
| 16 | + callCount.incrementAndGet() |
| 17 | + it.uppercase() |
| 18 | + } |
| 19 | + |
| 20 | + StepVerifier.create(resultMono).verifyComplete() // No value emitted, Mono completes directly |
| 21 | + Assertions.assertEquals(0, callCount.get()) |
| 22 | + } |
| 23 | + |
| 24 | + @Test |
| 25 | + fun `should provide default value for empty Mono`() { |
| 26 | + val emptyMono = Mono.empty<String>() |
| 27 | + val resultMono = emptyMono.defaultIfEmpty("Default Value") |
| 28 | + StepVerifier.create(resultMono) |
| 29 | + .expectNext("Default Value") |
| 30 | + .verifyComplete() |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + fun `should not override value for non-empty Mono`() { |
| 35 | + val nonEmptyMono = Mono.just("Actual Value") |
| 36 | + val resultMono = nonEmptyMono.defaultIfEmpty("Default Value") |
| 37 | + StepVerifier.create(resultMono) |
| 38 | + .expectNext("Actual Value") |
| 39 | + .verifyComplete() |
| 40 | + } |
| 41 | + |
| 42 | + @Test fun `should detect empty Mono using hasElement`() { |
| 43 | + val emptyMono = Mono.empty<String>() |
| 44 | + StepVerifier.create(emptyMono.hasElement()) |
| 45 | + .expectNext(false) |
| 46 | + .verifyComplete() |
| 47 | + } |
| 48 | + |
| 49 | + @Test fun `should detect non-empty Mono using hasElement`() { |
| 50 | + val nonEmptyMono = Mono.just("Hello, World!") |
| 51 | + StepVerifier.create(nonEmptyMono.hasElement()) |
| 52 | + .expectNext(true) |
| 53 | + .verifyComplete() |
| 54 | + } |
| 55 | + |
| 56 | + @Test |
| 57 | + fun `should provide fallback value for empty Mono`() { |
| 58 | + val emptyMono = Mono.empty<String>() |
| 59 | + val fallbackMono = emptyMono.switchIfEmpty(Mono.just("Fallback Value")) |
| 60 | + StepVerifier.create(fallbackMono) |
| 61 | + .expectNext("Fallback Value") |
| 62 | + .verifyComplete() |
| 63 | + } |
| 64 | + |
| 65 | + @Test |
| 66 | + fun `should not invoke fallback for non-empty Mono`() { |
| 67 | + val nonEmptyMono = Mono.just("Hello, World!") |
| 68 | + val resultMono = nonEmptyMono.switchIfEmpty(Mono.just("Fallback Value")) |
| 69 | + StepVerifier.create(resultMono) |
| 70 | + .expectNext("Hello, World!") |
| 71 | + .verifyComplete() |
| 72 | + } |
| 73 | +} |
0 commit comments