diff --git a/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java b/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java index 4fd21ec508..cf6a1e5ec5 100644 --- a/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java +++ b/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java @@ -16,7 +16,7 @@ import static org.hamcrest.MatcherAssert.assertThat; public class CollectorUtilsTests { @Test - public void maxByWithProjectionAndDefaultComparer() { + public void givenIntegerStream_whenCollectOnMaxByProjection_shouldReturnOptionalMaxValue() { Stream integerStream = Stream.of("a", "bb", "ccc", "1"); Optional max = integerStream.collect(maxBy(String::length)); @@ -25,7 +25,7 @@ public class CollectorUtilsTests { } @Test - public void minByWithProjectionAndDefaultComparer() { + public void givenIntegerStream_whenCollectOnMinByProjection_shouldReturnOptionalMinValue() { Stream integerStream = Stream.of("abc", "bb", "ccc", "1"); Optional max = integerStream.collect(minBy(String::length)); @@ -34,14 +34,14 @@ public class CollectorUtilsTests { } @Test - public void returnsEmptyForEmptyStream() { + public void givenEmptyStream_withCollectorUnique_shouldReturnEmpty() { assertThat(Stream .empty() .collect(CollectorUtils.unique()), equalTo(Optional.empty())); } @Test - public void returnsUniqueItem() { + public void givenIntegerStream_withCollectorUnique_shouldReturnUniqueValue() { assertThat(Stream .of(1, 2, 3) .filter(i -> i > 2) @@ -49,7 +49,7 @@ public class CollectorUtilsTests { } @Test - public void returnsUniqueNullableItem() { + public void givenIntegerStream_withUniqueNullable_shouldReturnUniqueValue() { assertThat(Stream .of(1, 2, 3) .filter(i -> i > 2) @@ -57,7 +57,7 @@ public class CollectorUtilsTests { } @Test(expected = NonUniqueValueException.class) - public void throwsExceptionIfItemIsNotUnique() { + public void givenIntegerStream_withCollectorUnique_shouldThrowNonUniqueValueException() { Stream .of(1, 2, 3) .filter(i -> i > 1) diff --git a/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java b/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java index 282a41e0df..37ca71287f 100644 --- a/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java +++ b/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java @@ -21,15 +21,7 @@ import static org.hamcrest.Matchers.*; public class StreamUtilsTests { @Test - public void createInfiniteIndex() { - LongStream indices = StreamUtils - .indices() - .limit(500); - - } - - @Test - public void zipAStreamWithIndex() { + public void givenStream_whenZipWithIndex_shouldReturnZippedStreamWithIndex() { Stream source = Stream.of("Foo", "Bar", "Baz"); List> zipped = StreamUtils @@ -40,7 +32,7 @@ public class StreamUtilsTests { } @Test - public void zipAPairOfStreams() { + public void givenTwoStreams_whenZip_shouldReturnZippedStream() { Stream streamA = Stream.of("A", "B", "C"); Stream streamB = Stream.of("Apple", "Banana", "Carrot"); @@ -52,7 +44,7 @@ public class StreamUtilsTests { } @Test - public void zipThreeStreams() { + public void givenThreeStreams_whenZip_shouldReturnZippedStream() { Stream streamA = Stream.of("A", "B", "C"); Stream streamB = Stream.of("aggravating", "banausic", "complaisant"); Stream streamC = Stream.of("Apple", "Banana", "Carrot"); @@ -65,7 +57,8 @@ public class StreamUtilsTests { } @Test - public void mergeThreeStreams() { + //givenThreeStreams_whenMerge_shouldReturnMergedStream + public void givenThreeStreams_whenMerge_shouldReturnMergedStream() { Stream streamA = Stream.of("A", "B", "C"); Stream streamB = Stream.of("apple", "banana", "carrot", "date"); Stream streamC = Stream.of("fritter", "split", "cake", "roll", "pastry"); @@ -76,7 +69,8 @@ public class StreamUtilsTests { } @Test - public void roundRobinInterleaving() { + //givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream + public void givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream() { Stream streamA = Stream.of("Peter", "Paul", "Mary"); Stream streamB = Stream.of("A", "B", "C", "D", "E"); Stream streamC = Stream.of("foo", "bar", "baz", "xyzzy"); @@ -87,7 +81,8 @@ public class StreamUtilsTests { } @Test - public void takeWhileConditionIsMet() { + //givenInfiniteStream_whenTakeWhile10_shouldReturnStreamOfSize10 + public void givenInfiniteStream_whenTakeWhile10_shouldReturnStream() { Stream infiniteInts = Stream.iterate(0, i -> i + 1); Stream finiteInts = StreamUtils.takeWhile(infiniteInts, i -> i < 10); @@ -95,7 +90,7 @@ public class StreamUtilsTests { } @Test - public void takeUntilConditionIsNotMet() { + public void givenInfiniteStream_whenTakeUntil10_shouldReturnStreamUpto10() { Stream infiniteInts = Stream.iterate(0, i -> i + 1); Stream finiteInts = StreamUtils.takeUntil(infiniteInts, i -> i > 10); @@ -103,7 +98,7 @@ public class StreamUtilsTests { } @Test - public void skipWhileConditionMet() { + public void givenIntegerStreamOfTen_whenSkipWhileLessThanFour_shouldReturnStreamFromFourToTen() { Stream ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Stream skipped = StreamUtils.skipWhile(ints, i -> i < 4); List collected = skipped.collect(Collectors.toList()); @@ -112,7 +107,7 @@ public class StreamUtilsTests { } @Test - public void skipUntilConditionMet() { + public void givenIntegerStreamOfTen_whenSkipUntilFour_shouldReturnStreamFromFiveToTen() { Stream ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Stream skipped = StreamUtils.skipUntil(ints, i -> i > 4); List collected = skipped.collect(Collectors.toList()); @@ -121,14 +116,14 @@ public class StreamUtilsTests { } @Test - public void unfoldUntilEmptyIsReturned() { + public void givenSeedValue_withUnfold_shouldReturnStreamAccordingToGeneratorMethod() { Stream unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty()); assertThat(unfolded.collect(Collectors.toList()), contains(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); } @Test - public void groupRunsStreamTest() { + public void giveIntegerStream_whenGroupRuns_shouldReturnListGroupItems() { Stream integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5); List> runs = StreamUtils .groupRuns(integerStream) @@ -138,14 +133,14 @@ public class StreamUtilsTests { } @Test - public void aggreagateOnBiElementPredicate() { + public void givenAStream_whenAggregate_shouldReturnAggregatedStreamOnTheBasisOfBiFunction() { Stream stream = Stream.of("a1", "b1", "b2", "c1"); Stream> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0)); assertThat(aggregated.collect(toList()), contains(asList("a1"), asList("b1", "b2"), asList("c1"))); } @Test - public void windowingOnList() { + public void givenIntegerStream_whenWindowed_shouldReturnListOfListOfItemsOfWindowSize() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); List> windows = StreamUtils @@ -156,7 +151,8 @@ public class StreamUtilsTests { } @Test - public void windowingOnListTwoOverlap() { + //givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip + public void givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); List> windows = StreamUtils @@ -167,7 +163,7 @@ public class StreamUtilsTests { } @Test - public void windowingOnEmptyList() { + public void givenEmptyStream_whenWindowed_shouldReturnIterableWithSizeZero() { ArrayList ints = new ArrayList<>(); ints @@ -184,7 +180,7 @@ public class StreamUtilsTests { } @Test - public void windowingOnListTwoOverlapAllowLesserSize() { + public void givenIntegerStream_whenWindowedWithWindowSizeAndSkipAndAllowLesserSize_shouldReturnListOfListOfInteger() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); List> windows = StreamUtils @@ -195,14 +191,12 @@ public class StreamUtilsTests { } @Test - public void windowingOnListOneOverlapAllowLesserSizeMultipleLesserWindows() { - Stream integerStream = Stream.of(1, 2, 3, 4, 5); + public void givenLimit_withIndices_shouldReturnLongStreamUptoLimit() { + LongStream indices = StreamUtils + .indices() + .limit(500); - List> windows = StreamUtils - .windowed(integerStream, 3, 1, true) - .collect(toList()); - - assertThat(windows, contains(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5), asList(5))); + assertThat(indices.count(), equalTo(500)); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java new file mode 100644 index 0000000000..8ce370e356 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java @@ -0,0 +1,273 @@ +package com.baeldung.rxjava; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import rx.Observable; +import rx.Observer; +import rx.exceptions.OnErrorNotImplementedException; +import rx.schedulers.Schedulers; + +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; + +public class UtilityOperatorsTest { + + int emittedTotal = 0; + int receivedTotal = 0; + String result = ""; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void givenObservable_whenObserveOnAfterOnNext_thenEmitsEventsOnComputeScheduler() throws InterruptedException { + + Observable.range(1, 5) + .map(i -> i * 100) + .doOnNext(i -> { + emittedTotal += i; + System.out.println("Emitting " + i + + " on thread " + Thread.currentThread().getName()); + }) + .observeOn(Schedulers.computation()) + .map(i -> i * 10) + .subscribe(i -> { + receivedTotal += i; + System.out.println("Received " + i + " on thread " + + Thread.currentThread().getName()); + }); + + Thread.sleep(2000); + assertTrue(emittedTotal == 1500); + assertTrue(receivedTotal == 15000); + } + + + @Test + public void givenObservable_whenObserveOnBeforeOnNext_thenEmitsEventsOnComputeScheduler() throws InterruptedException { + + Observable.range(1, 5) + .map(i -> i * 100) + .observeOn(Schedulers.computation()) + .doOnNext(i -> { + emittedTotal += i; + System.out.println("Emitting " + i + + " on thread " + Thread.currentThread().getName()); + }) + .map(i -> i * 10) + .subscribe(i -> { + receivedTotal += i; + System.out.println("Received " + i + " on thread " + + Thread.currentThread().getName()); + }); + + Thread.sleep(2000); + assertTrue(emittedTotal == 1500); + assertTrue(receivedTotal == 15000); + } + + + @Test + public void givenObservable_whenSubscribeOn_thenEmitsEventsOnComputeScheduler() throws InterruptedException { + + Observable.range(1, 5) + .map(i -> i * 100) + .doOnNext(i -> { + emittedTotal += i; + System.out.println("Emitting " + i + + " on thread " + Thread.currentThread().getName()); + }) + .subscribeOn(Schedulers.computation()) + .map(i -> i * 10) + .subscribe(i -> { + receivedTotal += i; + System.out.println("Received " + i + " on thread " + + Thread.currentThread().getName()); + }); + + Thread.sleep(2000); + assertTrue(emittedTotal == 1500); + assertTrue(receivedTotal == 15000); + } + + + @Test + public void givenObservableWithOneEvent_whenSingle_thenEmitEvent() { + + Observable.range(1, 1) + .single() + .subscribe(i -> receivedTotal += i); + assertTrue(receivedTotal == 1); + } + + @Test + public void givenObservableWithNoEvents_whenSingle_thenThrowException() { + + Observable.range(1, 3) + .single() + .onErrorReturn(e -> receivedTotal += 10) + .subscribe(); + assertTrue(receivedTotal == 10); + } + + @Test + public void givenObservableWihNoEvents_whenSingleOrDefault_thenDefaultMessage() { + + Observable.empty() + .singleOrDefault("Default") + .subscribe(i -> result += i); + assertTrue(result.equals("Default")); + } + + @Test + public void givenObservableWithManyEvents_whenSingleOrDefault_thenThrowException() { + + Observable.range(1, 3) + .singleOrDefault(5) + .onErrorReturn(e -> receivedTotal += 10) + .subscribe(); + assertTrue(receivedTotal == 10); + } + + @Test + public void givenObservable_whenDoOnNextAndDoOnCompleted_thenSumAllEventsAndShowMessage() { + + Observable.range(1, 10) + .doOnNext(r -> receivedTotal += r) + .doOnCompleted(() -> result = "Completed") + .subscribe(); + assertTrue(receivedTotal == 55); + assertTrue(result.equals("Completed")); + } + + @Test + public void givenObservable_whenDoOnEachAndDoOnSubscribe_thenSumAllValuesAndShowMessage() { + + Observable.range(1, 10) + .doOnEach(new Observer() { + @Override + public void onCompleted() { + System.out.println("Complete"); + } + + @Override + public void onError(Throwable e) { + e.printStackTrace(); + } + + @Override + public void onNext(Integer value) { + receivedTotal += value; + } + }) + .doOnSubscribe(() -> result = "Subscribed") + .subscribe(); + assertTrue(receivedTotal == 55); + assertTrue(result.equals("Subscribed")); + } + + @Test + public void givenObservable_whenDoOnErrorDoOnTerminateAndDoAfterTerminate_thenShowErrorTerminateAndAfterTerminateMessages() { + + thrown.expect(OnErrorNotImplementedException.class); + Observable.empty() + .single() + .doOnError(throwable -> { + throw new RuntimeException("error"); + }) + .doOnTerminate(() -> result += "doOnTerminate") + .doAfterTerminate(() -> result += "_doAfterTerminate") + .subscribe(); + assertTrue(result.equals("doOnTerminate_doAfterTerminate")); + } + + @Test + public void givenObservable_whenTimestamp_thenEventsShouldAppearTimestamped() { + + Observable.range(1, 10) + .timestamp() + .map(o -> result = o.getClass().toString()) + .last() + .subscribe(); + assertTrue(result.equals("class rx.schedulers.Timestamped")); + } + + @Test + public void givenObservables_whenDelay_thenEventsStartAppearAfterATime() throws InterruptedException { + + Observable source + = Observable.interval(1, TimeUnit.SECONDS) + .take(5) + .timestamp(); + + Observable delay + = source.delaySubscription(2, TimeUnit.SECONDS); + + source.subscribe( + value -> System.out.println("source :" + value), + t -> System.out.println("source error"), + () -> System.out.println("source completed")); + + delay.subscribe( + value -> System.out.println("delay : " + value), + t -> System.out.println("delay error"), + () -> System.out.println("delay completed")); + Thread.sleep(8000); + } + + @Test + public void givenObservable_whenRepeat_thenSumNumbersThreeTimes() { + + Observable.range(1, 3) + .repeat(3) + .subscribe(i -> receivedTotal += i); + assertTrue(receivedTotal == 18); + } + + @Test + public void givenObservable_whenUsing_thenReturnCreatedResource() { + + Observable values = Observable.using( + () -> "resource", + r -> { + return Observable.create(o -> { + for (Character c : r.toCharArray()) { + o.onNext(c); + } + o.onCompleted(); + }); + }, + r -> System.out.println("Disposed: " + r) + ); + values.subscribe( + v -> result += v, + e -> result += e + ); + assertTrue(result.equals("resource")); + } + + + @Test + public void givenObservableCached_whenSubscribesWith2Actions_thenEmitsCachedValues() { + + Observable source = + Observable.create(subscriber -> { + System.out.println("Create"); + subscriber.onNext(receivedTotal += 5); + subscriber.onCompleted(); + } + ).cache(); + source.subscribe(i -> { + System.out.println("element 1"); + receivedTotal += 1; + }); + source.subscribe(i -> { + System.out.println("element 2"); + receivedTotal += 2; + }); + assertTrue(receivedTotal == 8); + } + +} diff --git a/testing/pom.xml b/testing/pom.xml index 72ec2b2f0c..8f5c6ddb3d 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -86,6 +86,12 @@ jgotesting ${jgotesting.version} test + + + org.jukito + jukito + 1.5 + test diff --git a/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java b/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java new file mode 100644 index 0000000000..fd75e1bd9e --- /dev/null +++ b/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java @@ -0,0 +1,7 @@ +package com.baeldung.introductionjukito; + +public interface Calculator { + + public double add(double a, double b); + +} diff --git a/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java b/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java new file mode 100644 index 0000000000..2501569afc --- /dev/null +++ b/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java @@ -0,0 +1,5 @@ +package com.baeldung.introductionjukito; + +public class ScientificCalculator extends SimpleCalculator { + +} diff --git a/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java b/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java new file mode 100644 index 0000000000..933baa3cd0 --- /dev/null +++ b/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java @@ -0,0 +1,10 @@ +package com.baeldung.introductionjukito; + +public class SimpleCalculator implements Calculator { + + @Override + public double add(double a, double b) { + return a+b; + } + +} diff --git a/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java b/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java new file mode 100644 index 0000000000..313e1d2938 --- /dev/null +++ b/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java @@ -0,0 +1,62 @@ +package com.baeldung.introductionjukito; + +import org.jukito.All; +import org.jukito.JukitoModule; +import org.jukito.JukitoRunner; +import org.junit.Test; +import org.junit.runner.RunWith; +import static org.junit.Assert.*; + +@RunWith(JukitoRunner.class) +public class CalculatorTest { + + public static class Module extends JukitoModule { + + @Override + protected void configureTest() { + bindMany(Calculator.class, SimpleCalculator.class, + ScientificCalculator.class); + bindManyInstances(AdditionTest.class, new AdditionTest(1, 1, 2), + new AdditionTest(10, 10, 20), + new AdditionTest(18, 24, 42)); + bindManyNamedInstances(Integer.class, "even", 2, 4, 6); + bindManyNamedInstances(Integer.class, "odd", 1, 3, 5); + } + } + + public static class AdditionTest { + + int a; + int b; + int expected; + + public AdditionTest(int a, int b, int expected) { + this.a = a; + this.b = b; + this.expected = expected; + } + } + + @Test + public void givenTwoNumbers_WhenAdd_ThenSumBoth(@All Calculator calc) { + double result = calc.add(1, 1); + assertEquals(2, result, .1); + } + + @Test + public void givenTwoNumbers_WhenAdd_ThenSumBoth(@All Calculator calc, + @All AdditionTest addTest) { + double result = calc.add(addTest.a, addTest.b); + assertEquals(addTest.expected, result, .1); + } + + @Test + public void givenEvenNumbers_whenPrint_thenOutput(@All("even") Integer i) { + System.out.println("even " + i); + } + + @Test + public void givenOddNumbers_whenPrint_thenOutput(@All("odd") Integer i) { + System.out.println("odd " + i); + } +}