This commit is contained in:
Dassi Orleando 2017-09-27 20:55:22 +01:00
commit 395509b76f
33 changed files with 799 additions and 320 deletions

View File

@ -0,0 +1,57 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>animal-sniffer-mvn-plugin</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>example-animal-sniffer-mvn-plugin</name>
<url>http://maven.apache.org</url>
<properties>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
<version>1.16</version>
<configuration>
<signature>
<groupId>org.codehaus.mojo.signature</groupId>
<artifactId>java16</artifactId>
<version>1.0</version>
</signature>
</configuration>
<executions>
<execution>
<id>animal-sniffer</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,16 @@
package com.baeldung;
//import java.nio.charset.StandardCharsets;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
//System.out.println(StandardCharsets.UTF_8.name());
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}

View File

@ -10,6 +10,7 @@ import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class DirectoryWatcherExample {
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(System.getProperty("user.home"));
@ -21,5 +22,8 @@ public class DirectoryWatcherExample {
}
key.reset();
}
watchService.close();
}
}

View File

@ -585,6 +585,11 @@
<artifactId>fugue</artifactId>
<version>3.0.0-m007</version>
</dependency>
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
<repositories>
<repository>
@ -660,4 +665,4 @@
<cache.version>1.0.0</cache.version>
<hazelcast.version>3.8.4</hazelcast.version>
</properties>
</project>
</project>

View File

@ -1,85 +1,111 @@
package com.baeldung.commons.collections4;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.CollectionBag;
import org.apache.commons.collections4.bag.HashBag;
import org.apache.commons.collections4.bag.TreeBag;
import org.junit.Assert;
import org.junit.Before;
import org.apache.commons.collections4.SortedBag;
import org.apache.commons.collections4.bag.*;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
public class BagTests {
Bag<String> baseBag;
TreeBag<String> treeBag;
@Before
public void before() {
baseBag = new HashBag<String>();
treeBag = new TreeBag<String>();
treeBag = new TreeBag<String>();
}
@Test
public void whenAdd_thenRemoveFromBaseBag_thenContainsCorrect() {
baseBag.add("apple", 2);
baseBag.add("lemon", 6);
baseBag.add("lime");
baseBag.remove("lemon");
Assert.assertEquals(3, baseBag.size());
Assert.assertFalse(baseBag.contains("lemon"));
Assert.assertTrue(baseBag.uniqueSet().contains("apple"));
List<String> containList = new ArrayList<String>();
containList.add("apple");
containList.add("lemon");
containList.add("lime");
Assert.assertFalse(baseBag.containsAll(containList));
}
@Test
public void whenAdd_thenRemoveFromBaseCollectionBag_thenContainsCorrect() {
baseBag.add("apple", 2);
baseBag.add("lemon", 6);
baseBag.add("lime");
CollectionBag<String> baseCollectionBag = new CollectionBag<String>(
baseBag);
baseCollectionBag.remove("lemon");
Assert.assertEquals(8, baseCollectionBag.size());
Assert.assertTrue(baseCollectionBag.contains("lemon"));
baseCollectionBag.remove("lemon",1);
Assert.assertEquals(7, baseCollectionBag.size());
Assert.assertTrue(baseBag.uniqueSet().contains("apple"));
List<String> containList = new ArrayList<String>();
containList.add("apple");
containList.add("lemon");
containList.add("lime");
Assert.assertTrue(baseBag.containsAll(containList));
}
@Test
public void whenAddtoTreeBag_thenRemove_thenContainsCorrect() {
treeBag.add("banana", 8);
treeBag.add("apple", 2);
treeBag.add("lime");
Assert.assertEquals(11, treeBag.size());
Assert.assertEquals("apple", treeBag.first());
Assert.assertEquals("lime", treeBag.last());
treeBag.remove("apple");
Assert.assertEquals(9, treeBag.size());
Assert.assertEquals("banana", treeBag.first());
}
@Test
public void givenMultipleCopies_whenAdded_theCountIsKept() {
Bag<Integer> bag = new HashBag<>(
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
assertThat(bag.getCount(1), equalTo(2));
}
@Test
public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() {
Collection<Integer> collection = new ArrayList<>();
// Collection contract defines that add() should return true
assertThat(collection.add(9), is(true));
// Even when element is already in the collection
collection.add(1);
assertThat(collection.add(1), is(true));
Bag<Integer> bag = new HashBag<>();
// Bag returns true on adding a new element
assertThat(bag.add(9), is(true));
bag.add(1);
// But breaks the contract with false when it has to increment the count
assertThat(bag.add(1), is(not(true)));
}
@Test
public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() {
Bag<Integer> bag = CollectionBag.collectionBag(new HashBag<>());
bag.add(1);
// This time the behavior is compliant to the Java Collection
assertThat(bag.add(1), is((true)));
}
@Test
public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() {
Bag<Integer> bag = new HashBag<>();
// Adding 1 for 5 times
bag.add(1, 5);
assertThat(bag.getCount(1), equalTo(5));
}
@Test
public void givenMultipleCopies_whenRemove_allAreRemoved() {
Bag<Integer> bag = new HashBag<>(
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
// From 3 we delete 1, 2 remain
bag.remove(3, 1);
assertThat(bag.getCount(3), equalTo(2));
// From 2 we delete all
bag.remove(1);
assertThat(bag.getCount(1), equalTo(0));
}
@Test
public void givenTree_whenDuplicateElementsAdded_thenSort() {
TreeBag<Integer> bag = new TreeBag<>(
Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2));
assertThat(bag.last(), equalTo(7));
assertThat(bag.getCount(bag.last()), equalTo(3));
}
@Test
public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() {
SortedBag<Integer> bag = CollectionSortedBag
.collectionSortedBag(new TreeBag<>());
bag.add(1);
assertThat(bag.add(1), is((true)));
}
@Test
public void givenSortedBag_whenDuplicateElementsAdded_thenSort() {
SynchronizedSortedBag<Integer> bag = SynchronizedSortedBag
.synchronizedSortedBag(new TreeBag<>(
Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2));
assertThat(bag.last(), equalTo(7));
assertThat(bag.getCount(bag.last()), equalTo(3));
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.jgrapht.VertexFactory;
import org.jgrapht.alg.HamiltonianCycle;
import org.jgrapht.generate.CompleteGraphGenerator;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before;
import org.junit.Test;
public class CompleteGraphTest {
static SimpleWeightedGraph<String, DefaultEdge> completeGraph;
static int size = 10;
@Before
public void createCompleteGraph() {
completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
CompleteGraphGenerator<String, DefaultEdge> completeGenerator = new CompleteGraphGenerator<String, DefaultEdge>(size);
VertexFactory<String> vFactory = new VertexFactory<String>() {
private int id = 0;
public String createVertex() {
return "v" + id++;
}
};
completeGenerator.generateGraph(completeGraph, vFactory, null);
}
@Test
public void givenCompleteGraph_whenGetHamiltonianCyclePath_thenGetVerticeListInSequence() {
List<String> verticeList = HamiltonianCycle.getApproximateOptimalForCompleteGraph(completeGraph);
assertEquals(verticeList.size(), completeGraph.vertexSet().size());
}
}

View File

@ -0,0 +1,95 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;
import org.jgrapht.DirectedGraph;
import org.jgrapht.GraphPath;
import org.jgrapht.alg.CycleDetector;
import org.jgrapht.alg.KosarajuStrongConnectivityInspector;
import org.jgrapht.alg.interfaces.StrongConnectivityAlgorithm;
import org.jgrapht.alg.shortestpath.AllDirectedPaths;
import org.jgrapht.alg.shortestpath.BellmanFordShortestPath;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DirectedSubgraph;
import org.jgrapht.traverse.BreadthFirstIterator;
import org.jgrapht.traverse.DepthFirstIterator;
import org.junit.Before;
import org.junit.Test;
public class DirectedGraphTests {
DirectedGraph<String, DefaultEdge> directedGraph;
@Before
public void createDirectedGraph() {
directedGraph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
IntStream.range(1, 10).forEach(i -> {
directedGraph.addVertex("v" + i);
});
directedGraph.addEdge("v1", "v2");
directedGraph.addEdge("v2", "v4");
directedGraph.addEdge("v4", "v3");
directedGraph.addEdge("v3", "v1");
directedGraph.addEdge("v5", "v4");
directedGraph.addEdge("v5", "v6");
directedGraph.addEdge("v6", "v7");
directedGraph.addEdge("v7", "v5");
directedGraph.addEdge("v8", "v5");
directedGraph.addEdge("v9", "v8");
}
@Test
public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() {
StrongConnectivityAlgorithm<String, DefaultEdge> scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph);
List<DirectedSubgraph<String, DefaultEdge>> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs();
List<String> stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet());
String randomVertex1 = stronglyConnectedVertices.get(0);
String randomVertex2 = stronglyConnectedVertices.get(3);
AllDirectedPaths<String, DefaultEdge> allDirectedPaths = new AllDirectedPaths<>(directedGraph);
List<GraphPath<String, DefaultEdge>> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size());
assertTrue(possiblePathList.size() > 0);
}
@Test
public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() {
CycleDetector<String, DefaultEdge> cycleDetector = new CycleDetector<String, DefaultEdge>(directedGraph);
assertTrue(cycleDetector.detectCycles());
Set<String> cycleVertices = cycleDetector.findCycles();
assertTrue(cycleVertices.size() > 0);
}
@Test
public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() {
DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph);
assertNotNull(depthFirstIterator);
}
@Test
public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() {
BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph);
assertNotNull(breadthFirstIterator);
}
@Test
public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() {
DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph);
List<String> shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList();
assertNotNull(shortestPath);
}
@Test
public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() {
BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph);
List<String> shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList();
assertNotNull(shortestPath);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.stream.IntStream;
import org.jgrapht.GraphPath;
import org.jgrapht.alg.cycle.HierholzerEulerianCycle;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before;
import org.junit.Test;
public class EulerianCircuitTest {
SimpleWeightedGraph<String, DefaultEdge> simpleGraph;
@Before
public void createGraphWithEulerianCircuit() {
simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
IntStream.range(1, 6).forEach(i -> {
simpleGraph.addVertex("v" + i);
});
IntStream.range(1, 6).forEach(i -> {
int endVertexNo = (i + 1) > 5 ? 1 : i + 1;
simpleGraph.addEdge("v" + i, "v" + endVertexNo);
});
}
@Test
public void givenGraph_whenCheckEluerianCycle_thenGetResult() {
HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>();
assertTrue(eulerianCycle.isEulerian(simpleGraph));
}
@Test
public void givenGraphWithEulerianCircuit_whenGetEulerianCycle_thenGetGraphPath() {
HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>();
GraphPath path = eulerianCycle.getEulerianCycle(simpleGraph);
assertTrue(path.getEdgeList().containsAll(simpleGraph.edgeSet()));
}
}

View File

@ -3,7 +3,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>rxjava</artifactId>
<version>1.0-SNAPSHOT</version>
@ -47,6 +46,12 @@
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>

View File

@ -8,7 +8,7 @@ import static junit.framework.Assert.assertTrue;
public class ObservableTest {
String result = "";
private String result = "";
@Test
public void givenString_whenJustAndSubscribe_thenEmitsSingleItem() {
@ -85,7 +85,7 @@ public class ObservableTest {
.groupBy(i -> 0 == (i % 2) ? "EVEN" : "ODD")
.subscribe(group ->
group.subscribe((number) -> {
if (group.getKey().toString().equals("EVEN")) {
if (group.getKey().equals("EVEN")) {
EVEN[0] += number;
} else {
ODD[0] += number;
@ -141,5 +141,4 @@ public class ObservableTest {
assertTrue(sum[0] == 10);
}
}

View File

@ -12,16 +12,12 @@ public class ResourceManagementTest {
String[] result = {""};
Observable<Character> values = Observable.using(
() -> {
return "MyResource";
},
r -> {
return Observable.create(o -> {
for (Character c : r.toCharArray())
o.onNext(c);
o.onCompleted();
});
},
() -> "MyResource",
r -> Observable.create(o -> {
for (Character c : r.toCharArray())
o.onNext(c);
o.onCompleted();
}),
r -> System.out.println("Disposed: " + r)
);

View File

@ -27,7 +27,6 @@ public class RxJavaBackpressureLongRunningUnitTest {
// then
testSubscriber.awaitTerminalEvent();
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
@ -60,7 +59,6 @@ public class RxJavaBackpressureLongRunningUnitTest {
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
@ -77,7 +75,6 @@ public class RxJavaBackpressureLongRunningUnitTest {
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
@ -88,15 +85,14 @@ public class RxJavaBackpressureLongRunningUnitTest {
// when
source.sample(100, TimeUnit.MILLISECONDS)
// .throttleFirst(100, TimeUnit.MILLISECONDS)
.observeOn(Schedulers.computation()).subscribe(testSubscriber);
// .throttleFirst(100, TimeUnit.MILLISECONDS)
.observeOn(Schedulers.computation()).subscribe(testSubscriber);
IntStream.range(0, 1_000).forEach(source::onNext);
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
@ -111,7 +107,6 @@ public class RxJavaBackpressureLongRunningUnitTest {
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
@ -120,11 +115,11 @@ public class RxJavaBackpressureLongRunningUnitTest {
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
// when
Observable.range(1, 1_000_000).onBackpressureDrop().observeOn(Schedulers.computation()).subscribe(testSubscriber);
Observable.range(1, 1_000_000).onBackpressureDrop().observeOn(Schedulers.computation())
.subscribe(testSubscriber);
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
}

View File

@ -1,5 +1,15 @@
package com.baeldung.rxjava;
import org.junit.Test;
import rx.Observable;
import rx.Observable.Operator;
import rx.Observable.Transformer;
import rx.Subscriber;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.baelding.rxjava.operator.ToCleanString.toCleanString;
import static com.baelding.rxjava.operator.ToLength.toLength;
import static org.hamcrest.Matchers.hasItems;
@ -7,20 +17,6 @@ import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import rx.Observable;
import rx.Observable.Operator;
import rx.Observable.Transformer;
import rx.Subscriber;
import com.baelding.rxjava.operator.ToCleanString;
import com.baelding.rxjava.operator.ToLength;
public class RxJavaCustomOperatorUnitTest {
@Test
@ -29,7 +25,7 @@ public class RxJavaCustomOperatorUnitTest {
final List<String> results = new ArrayList<>();
final Observable<String> observable = Observable.from(list)
.lift(toCleanString());
.lift(toCleanString());
// when
observable.subscribe(results::add);
@ -46,7 +42,7 @@ public class RxJavaCustomOperatorUnitTest {
final List<Integer> results = new ArrayList<>();
final Observable<Integer> observable = Observable.from(list)
.compose(toLength());
.compose(toLength());
// when
observable.subscribe(results::add);
@ -85,8 +81,8 @@ public class RxJavaCustomOperatorUnitTest {
final List<String> results = new ArrayList<>();
Observable.from(Arrays.asList("ap_p-l@e", "or-an?ge"))
.lift(cleanStringFn)
.subscribe(results::add);
.lift(cleanStringFn)
.subscribe(results::add);
assertThat(results, notNullValue());
assertThat(results, hasSize(2));
@ -99,8 +95,8 @@ public class RxJavaCustomOperatorUnitTest {
final List<Integer> results = new ArrayList<>();
Observable.from(Arrays.asList("apple", "orange"))
.compose(toLengthFn)
.subscribe(results::add);
.compose(toLengthFn)
.subscribe(results::add);
assertThat(results, notNullValue());
assertThat(results, hasSize(2));

View File

@ -10,7 +10,9 @@ import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
public class RxJavaUnitTest {
@ -19,7 +21,8 @@ public class RxJavaUnitTest {
// given
List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
List<String> results = new ArrayList<>();
Observable<String> observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), (string, index) -> index + "-" + string);
Observable<String> observable = Observable.from(letters)
.zipWith(Observable.range(1, Integer.MAX_VALUE), (string, index) -> index + "-" + string);
// when
observable.subscribe(results::add);
@ -36,7 +39,8 @@ public class RxJavaUnitTest {
List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
TestSubscriber<String> subscriber = new TestSubscriber<>();
Observable<String> observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string));
Observable<String> observable = Observable.from(letters)
.zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string));
// when
observable.subscribe(subscriber);
@ -54,7 +58,9 @@ public class RxJavaUnitTest {
List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
TestSubscriber<String> subscriber = new TestSubscriber<>();
Observable<String> observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string)).concatWith(Observable.error(new RuntimeException("error in Observable")));
Observable<String> observable = Observable.from(letters)
.zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string))
.concatWith(Observable.error(new RuntimeException("error in Observable")));
// when
observable.subscribe(subscriber);

View File

@ -0,0 +1,235 @@
package com.baeldung.rxjava;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import rx.Observable;
import rx.Scheduler;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import rx.schedulers.TestScheduler;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.assertThat;
public class SchedulersTest {
private String result = "";
private String result1 = "";
private String result2 = "";
@Test
public void givenScheduledWorker_whenScheduleAnAction_thenResultAction() throws InterruptedException {
System.out.println("scheduling");
Scheduler scheduler = Schedulers.immediate();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> result += "action");
Assert.assertTrue(result.equals("action"));
}
@Test
public void givenScheduledWorker_whenUnsubscribeOnWorker_thenResultFirstAction() throws InterruptedException {
System.out.println("canceling");
Scheduler scheduler = Schedulers.newThread();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> {
result += "First_Action";
worker.unsubscribe();
});
worker.schedule(() -> result += "Second_Action");
Thread.sleep(500);
Assert.assertTrue(result.equals("First_Action"));
}
@Ignore //it's not safe, not every time is running correctly
@Test
public void givenWorker_whenScheduledOnNewThread_thenResultIsBoundToNewThread() throws InterruptedException {
System.out.println("newThread_1");
Scheduler scheduler = Schedulers.newThread();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> {
result += Thread.currentThread().getName() + "_Start";
worker.schedule(() -> result += "_worker_");
result += "_End";
});
Thread.sleep(2000);
Assert.assertTrue(result.equals("RxNewThreadScheduler-1_Start_End_worker_"));
}
@Test
public void givenObservable_whenObserveOnNewThread_thenRunOnDifferentThreadEachTime() throws InterruptedException {
System.out.println("newThread_2");
Observable.just("Hello")
.observeOn(Schedulers.newThread())
.doOnNext(s ->
result2 += Thread.currentThread().getName()
)
.observeOn(Schedulers.newThread())
.subscribe(s ->
result1 += Thread.currentThread().getName()
);
Thread.sleep(500);
Assert.assertTrue(result1.equals("RxNewThreadScheduler-1"));
Assert.assertTrue(result2.equals("RxNewThreadScheduler-2"));
}
@Test
public void givenWorker_whenScheduledOnImmediate_thenResultIsBoundToThread() throws InterruptedException {
System.out.println("immediate_1");
Scheduler scheduler = Schedulers.immediate();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> {
result += Thread.currentThread().getName() + "_Start";
worker.schedule(() -> result += "_worker_");
result += "_End";
});
Thread.sleep(500);
Assert.assertTrue(result.equals("main_Start_worker__End"));
}
@Test
public void givenObservable_whenImmediateScheduled_thenExecuteOnMainThread() throws InterruptedException {
System.out.println("immediate_2");
Observable.just("Hello")
.subscribeOn(Schedulers.immediate())
.subscribe(s ->
result += Thread.currentThread().getName()
);
Thread.sleep(500);
Assert.assertTrue(result.equals("main"));
}
@Test
public void givenObservable_whenTrampolineScheduled_thenExecuteOnMainThread() throws InterruptedException {
System.out.println("trampoline_1");
Observable.just(2, 4, 6, 8)
.subscribeOn(Schedulers.trampoline())
.subscribe(i -> result += "" + i);
Observable.just(1, 3, 5, 7, 9)
.subscribeOn(Schedulers.trampoline())
.subscribe(i -> result += "" + i);
Thread.sleep(500);
Assert.assertTrue(result.equals("246813579"));
}
@Test
public void givenWorker_whenScheduledOnTrampoline_thenComposeResultAsBlocking() throws InterruptedException {
System.out.println("trampoline_2");
Scheduler scheduler = Schedulers.trampoline();
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(() -> {
result += Thread.currentThread().getName() + "Start";
worker.schedule(() -> {
result += "_middleStart";
worker.schedule(() ->
result += "_worker_"
);
result += "_middleEnd";
});
result += "_mainEnd";
});
Thread.sleep(500);
Assert.assertTrue(result
.equals("mainStart_mainEnd_middleStart_middleEnd_worker_"));
}
private ThreadFactory threadFactory(String pattern) {
return new ThreadFactoryBuilder()
.setNameFormat(pattern)
.build();
}
@Test
public void givenExecutors_whenSchedulerFromCreatedExecutors_thenReturnElementsOnEacheThread() throws InterruptedException {
System.out.println("from");
ExecutorService poolA = newFixedThreadPool(10, threadFactory("Sched-A-%d"));
Scheduler schedulerA = Schedulers.from(poolA);
ExecutorService poolB = newFixedThreadPool(10, threadFactory("Sched-B-%d"));
Scheduler schedulerB = Schedulers.from(poolB);
Observable<String> observable = Observable.create(subscriber -> {
subscriber.onNext("Alfa");
subscriber.onNext("Beta");
subscriber.onCompleted();
});
;
observable
.subscribeOn(schedulerA)
.subscribeOn(schedulerB)
.subscribe(
x -> result += Thread.currentThread().getName() + x + "_",
Throwable::printStackTrace,
() -> result += "_Completed"
);
Thread.sleep(2000);
Assert.assertTrue(result.equals("Sched-A-0Alfa_Sched-A-0Beta__Completed"));
}
@Test
public void givenObservable_whenIoScheduling_thenReturnThreadName() throws InterruptedException {
System.out.println("io");
Observable.just("io")
.subscribeOn(Schedulers.io())
.subscribe(i -> result += Thread.currentThread().getName());
Thread.sleep(500);
Assert.assertTrue(result.equals("RxIoScheduler-2"));
}
@Test
public void givenObservable_whenComputationScheduling_thenReturnThreadName() throws InterruptedException {
System.out.println("computation");
Observable.just("computation")
.subscribeOn(Schedulers.computation())
.subscribe(i -> result += Thread.currentThread().getName());
Thread.sleep(500);
Assert.assertTrue(result.equals("RxComputationScheduler-1"));
}
@Test
public void givenLetters_whenTestScheduling_thenReturnValuesControllingAdvanceTime() throws InterruptedException {
List<String> letters = Arrays.asList("A", "B", "C");
TestScheduler scheduler = Schedulers.test();
TestSubscriber<String> subscriber = new TestSubscriber<>();
Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler);
Observable.from(letters)
.zipWith(tick, (string, index) -> index + "-" + string)
.subscribeOn(scheduler)
.subscribe(subscriber);
subscriber.assertNoValues();
subscriber.assertNotCompleted();
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValues("0-A");
scheduler.advanceTimeTo(3, TimeUnit.SECONDS);
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(3);
assertThat(subscriber.getOnNextEvents(), hasItems("0-A", "1-B", "2-C"));
}
@Test
public void givenLetters_whenDelay_thenReturne() throws InterruptedException {
ExecutorService poolA = newFixedThreadPool(10, threadFactory("Sched1-"));
Scheduler schedulerA = Schedulers.from(poolA);
Observable.just('A', 'B')
.delay(1, TimeUnit.SECONDS, schedulerA)
.subscribe(i -> result += Thread.currentThread().getName() + i + " ");
Thread.sleep(2000);
Assert.assertTrue(result.equals("Sched1-A Sched1-B "));
}
}

View File

@ -20,5 +20,4 @@ public class SingleTest {
single.subscribe();
assertTrue(result[0].equals("Hello"));
}
}

View File

@ -9,7 +9,7 @@ import static junit.framework.Assert.assertTrue;
public class SubjectTest {
@Test
public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd(){
public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd() {
PublishSubject<Integer> subject = PublishSubject.create();
subject.subscribe(SubjectImpl.getFirstObserver());

View File

@ -7,6 +7,7 @@ import rx.Observable;
import rx.Observer;
import rx.exceptions.OnErrorNotImplementedException;
import rx.schedulers.Schedulers;
import rx.schedulers.Timestamped;
import java.util.concurrent.TimeUnit;
@ -14,9 +15,9 @@ import static org.junit.Assert.assertTrue;
public class UtilityOperatorsTest {
int emittedTotal = 0;
int receivedTotal = 0;
String result = "";
private int emittedTotal = 0;
private int receivedTotal = 0;
private String result = "";
@Rule
public ExpectedException thrown = ExpectedException.none();
@ -44,7 +45,6 @@ public class UtilityOperatorsTest {
assertTrue(receivedTotal == 15000);
}
@Test
public void givenObservable_whenObserveOnBeforeOnNext_thenEmitsEventsOnComputeScheduler() throws InterruptedException {
@ -68,7 +68,6 @@ public class UtilityOperatorsTest {
assertTrue(receivedTotal == 15000);
}
@Test
public void givenObservable_whenSubscribeOn_thenEmitsEventsOnComputeScheduler() throws InterruptedException {
@ -92,7 +91,6 @@ public class UtilityOperatorsTest {
assertTrue(receivedTotal == 15000);
}
@Test
public void givenObservableWithOneEvent_whenSingle_thenEmitEvent() {
@ -197,15 +195,13 @@ public class UtilityOperatorsTest {
@Test
public void givenObservables_whenDelay_thenEventsStartAppearAfterATime() throws InterruptedException {
Observable source
= Observable.interval(1, TimeUnit.SECONDS)
Observable<Timestamped<Long>> source = Observable.interval(1, TimeUnit.SECONDS)
.take(5)
.timestamp();
Observable delay
= source.delaySubscription(2, TimeUnit.SECONDS);
Observable<Timestamped<Long>> delay = source.delaySubscription(2, TimeUnit.SECONDS);
source.subscribe(
source.<Long>subscribe(
value -> System.out.println("source :" + value),
t -> System.out.println("source error"),
() -> System.out.println("source completed"));
@ -231,14 +227,12 @@ public class UtilityOperatorsTest {
Observable<Character> values = Observable.using(
() -> "resource",
r -> {
return Observable.create(o -> {
for (Character c : r.toCharArray()) {
o.onNext(c);
}
o.onCompleted();
});
},
r -> Observable.create(o -> {
for (Character c : r.toCharArray()) {
o.onNext(c);
}
o.onCompleted();
}),
r -> System.out.println("Disposed: " + r)
);
values.subscribe(
@ -248,7 +242,6 @@ public class UtilityOperatorsTest {
assertTrue(result.equals("resource"));
}
@Test
public void givenObservableCached_whenSubscribesWith2Actions_thenEmitsCachedValues() {
@ -269,5 +262,4 @@ public class UtilityOperatorsTest {
});
assertTrue(receivedTotal == 8);
}
}

View File

@ -8,18 +8,16 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class AutomapClassTest {
public class AutomapClassIntegrationTest {
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private Database db = Database.from(Connector.connectionProvider);
Observable<Integer> create = null;
Observable<Integer> insert1, insert2 = null;
private Observable<Integer> create = null;
private Observable<Integer> insert1, insert2 = null;
@Before
public void setup() {
@ -58,6 +56,6 @@ public class AutomapClassTest {
public void close() {
db.update("DROP TABLE MANAGER")
.dependsOn(create);
connectionProvider.close();
Connector.connectionProvider.close();
}
}

View File

@ -8,18 +8,16 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class AutomapInterfaceTest {
public class AutomapInterfaceIntegrationTest {
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private Database db = Database.from(Connector.connectionProvider);
Observable<Integer> create = null;
Observable<Integer> insert1, insert2 = null;
private Observable<Integer> create = null;
private Observable<Integer> insert1, insert2 = null;
@Before
public void setup() {
@ -58,7 +56,7 @@ public class AutomapInterfaceTest {
public void close() {
db.update("DROP TABLE EMPLOYEE")
.dependsOn(create);
connectionProvider.close();
Connector.connectionProvider.close();
}
}

View File

@ -1,42 +1,38 @@
package com.baeldung.rxjava.jdbc;
import static org.junit.Assert.assertEquals;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Test;
import rx.Observable;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
public class BasicQueryTypesIntegrationTest {
import rx.Observable;
private Database db = Database.from(Connector.connectionProvider);
public class BasicQueryTypesTest {
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
Observable<Integer> create, insert1, insert2, insert3, update, delete = null;
private Observable<Integer> create;
@Test
public void whenCreateTableAndInsertRecords_thenCorrect() {
create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))")
.count();
insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')")
Observable<Integer> insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')")
.dependsOn(create)
.count();
update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1")
Observable<Integer> update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1")
.dependsOn(create)
.count();
insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')")
Observable<Integer> insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')")
.dependsOn(create)
.count();
insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')")
Observable<Integer> insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')")
.dependsOn(create)
.count();
delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2")
Observable<Integer> delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2")
.dependsOn(create)
.count();
List<String> names = db.select("select name from EMPLOYEE where id < ?")
@ -59,6 +55,6 @@ public class BasicQueryTypesTest {
public void close() {
db.update("DROP TABLE EMPLOYEE")
.dependsOn(create);
connectionProvider.close();
Connector.connectionProvider.close();
}
}

View File

@ -1,30 +1,26 @@
package com.baeldung.rxjava.jdbc;
import static org.junit.Assert.assertEquals;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Observable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
public class InsertBlobIntegrationTest {
import rx.Observable;
private Database db = Database.from(Connector.connectionProvider);
public class InsertBlobTest {
private String expectedDocument = null;
private String actualDocument = null;
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
String expectedDocument = null;
String actualDocument = null;
Observable<Integer> create, insert = null;
private Observable<Integer> create, insert = null;
@Before
public void setup() throws IOException {
@ -60,6 +56,6 @@ public class InsertBlobTest {
public void close() {
db.update("DROP TABLE SERVERLOG")
.dependsOn(create);
connectionProvider.close();
Connector.connectionProvider.close();
}
}

View File

@ -1,29 +1,25 @@
package com.baeldung.rxjava.jdbc;
import static org.junit.Assert.assertEquals;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Observable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
public class InsertClobIntegrationTest {
import rx.Observable;
private Database db = Database.from(Connector.connectionProvider);
public class InsertClobTest {
private String expectedDocument = null;
private String actualDocument = null;
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
String expectedDocument = null;
String actualDocument = null;
Observable<Integer> create, insert = null;
private Observable<Integer> create, insert = null;
@Before
public void setup() throws IOException {
@ -58,6 +54,6 @@ public class InsertClobTest {
public void close() {
db.update("DROP TABLE SERVERLOG")
.dependsOn(create);
connectionProvider.close();
Connector.connectionProvider.close();
}
}

View File

@ -1,28 +1,24 @@
package com.baeldung.rxjava.jdbc;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class ReturnKeysTest {
import static org.assertj.core.api.Assertions.assertThat;
Observable<Boolean> begin, commit = null;
Observable<Integer> createStatement, insertStatement, updateStatement = null;
public class ReturnKeysIntegrationTest {
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private Observable<Integer> createStatement;
private Database db = Database.from(Connector.connectionProvider);
@Before
public void setup() {
begin = db.beginTransaction();
createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))")
Observable<Boolean> begin = db.beginTransaction();
createStatement = db
.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))")
.dependsOn(begin)
.count();
}
@ -41,8 +37,7 @@ public class ReturnKeysTest {
@After
public void close() {
db.update("DROP TABLE EMPLOYEE")
.dependsOn(createStatement);
connectionProvider.close();
db.update("DROP TABLE EMPLOYEE");
Connector.connectionProvider.close();
}
}

View File

@ -1,22 +1,15 @@
package com.baeldung.rxjava.jdbc;
import com.github.davidmoten.rx.jdbc.Database;
import org.junit.After;
import org.junit.Test;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Test;
public class TransactionIntegrationTest {
import com.github.davidmoten.rx.jdbc.ConnectionProvider;
import com.github.davidmoten.rx.jdbc.Database;
import rx.Observable;
public class TransactionTest {
Observable<Boolean> begin, commit = null;
Observable<Integer> createStatement, insertStatement, updateStatement = null;
ConnectionProvider connectionProvider = Connector.connectionProvider;
Database db = Database.from(connectionProvider);
private Database db = Database.from(Connector.connectionProvider);
@Test
public void whenCommitTransaction_thenRecordUpdated() {
@ -43,8 +36,7 @@ public class TransactionTest {
@After
public void close() {
db.update("DROP TABLE EMPLOYEE")
.dependsOn(createStatement);
connectionProvider.close();
db.update("DROP TABLE EMPLOYEE");
Connector.connectionProvider.close();
}
}

View File

@ -9,9 +9,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.assertTrue;
/**
* @author aiet
*/
public class ExceptionHandlingTest {
private Error UNKNOWN_ERROR = new Error("unknown error");
@ -19,10 +16,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenHandleOnErrorReturn_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.onErrorReturn(Throwable::getMessage)
.subscribe(testObserver);
@ -34,10 +31,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenHandleOnErrorResume_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.onErrorResumeNext(Observable.just("one", "two"))
.subscribe(testObserver);
@ -49,10 +46,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenHandleOnErrorResumeItem_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.onErrorReturnItem("singleValue")
.subscribe(testObserver);
@ -64,10 +61,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenHandleOnErrorResumeFunc_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.onErrorResumeNext(throwable -> {
return Observable.just(throwable.getMessage(), "nextValue");
})
@ -81,11 +78,11 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenChangeStateOnError_thenErrorThrown() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
final AtomicBoolean state = new AtomicBoolean(false);
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.doOnError(throwable -> state.set(true))
.subscribe(testObserver);
@ -97,10 +94,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenExceptionOccurOnError_thenCompositeExceptionThrown() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.doOnError(throwable -> {
throw new RuntimeException("unexcepted");
})
@ -113,10 +110,10 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndException_whenHandleOnException_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_EXCEPTION)
.<String>error(UNKNOWN_EXCEPTION)
.onExceptionResumeNext(Observable.just("exceptionResumed"))
.subscribe(testObserver);
@ -128,14 +125,14 @@ public class ExceptionHandlingTest {
@Test
public void givenSubscriberAndError_whenHandleOnException_thenNotResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.onExceptionResumeNext(Observable.just("exceptionResumed"))
.subscribe(testObserver);
testObserver.assertError(UNKNOWN_ERROR);
testObserver.assertNotComplete();
}
}

View File

@ -9,20 +9,17 @@ import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertTrue;
/**
* @author aiet
*/
public class OnErrorRetryTest {
private Error UNKNOWN_ERROR = new Error("unknown error");
@Test
public void givenSubscriberAndError_whenRetryOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
.<String>error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
@ -37,12 +34,12 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryConditionallyOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
.<String>error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
@ -57,11 +54,11 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryUntilOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.retryUntil(() -> atomicCounter.incrementAndGet() > 3)
.subscribe(testObserver);
@ -73,12 +70,12 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
Exception noretryException = new Exception("don't retry");
Observable
.error(UNKNOWN_ERROR)
.retryWhen(throwableObservable -> Observable.error(noretryException))
.<String>error(UNKNOWN_ERROR)
.retryWhen(throwableObservable -> Observable.<String>error(noretryException))
.subscribe(testObserver);
testObserver.assertError(noretryException);
@ -88,11 +85,11 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenCompleted() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
.<String>error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
@ -107,11 +104,11 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenResubscribed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
.<String>error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
@ -126,11 +123,11 @@ public class OnErrorRetryTest {
@Test
public void givenSubscriberAndError_whenRetryWhenForMultipleTimesOnError_thenResumed() {
TestObserver testObserver = new TestObserver();
TestObserver<String> testObserver = new TestObserver<>();
long before = System.currentTimeMillis();
Observable
.error(UNKNOWN_ERROR)
.<String>error(UNKNOWN_ERROR)
.retryWhen(throwableObservable -> throwableObservable
.zipWith(Observable.range(1, 3), (throwable, integer) -> integer)
.flatMap(integer -> {

View File

@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MainApplication.class)
public class ExamplePostControllerRequestUnitTest {
public class ExamplePostControllerRequestIntegrationTest {
MockMvc mockMvc;
@Mock private ExampleService exampleService;

View File

@ -23,7 +23,7 @@ import org.baeldung.config.MainApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MainApplication.class)
public class ExamplePostControllerResponseUnitTest {
public class ExamplePostControllerResponseIntegrationTest {
MockMvc mockMvc;
@Mock private ExampleService exampleService;

View File

@ -1,33 +0,0 @@
package com.baeldung.web.log.test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.baeldung.web.log.data.TaxiRide;
public class TestTaxiFareController {
private static final String URL = "http://localhost:" + 8082 + "/spring-rest/taxifare/";
@Test
public void givenRequest_whenFetchTaxiFareRateCard_thanOK() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> response = testRestTemplate.getForEntity(URL + "get/", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenTaxiRide_whenCalculatedFare_thanStatus200() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
TaxiRide taxiRide = new TaxiRide(true, 10l);
String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide, String.class);
assertThat(fare, equalTo("200"));
}
}

View File

@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com
- [Two Login Pages with Spring Security](http://www.baeldung.com/spring-security-two-login-pages)
- [Multiple Entry Points in Spring Security](http://www.baeldung.com/spring-security-multiple-entry-points)
- [Multiple Authentication Providers in Spring Security](http://www.baeldung.com/spring-security-multiple-auth-providers)
- [Granted Authority Versus Role in Spring Security](http://www.baeldung.com/spring-security-granted-authority-vs-role)

View File

@ -5,4 +5,4 @@
- [Property Testing Example With Vavr](http://www.baeldung.com/javaslang-property-testing)
- [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr)
- [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr)
- [Collection Factory Methods for Vavr](http://www.baeldung.com/vavr-collection-factory-methods)