Merge remote-tracking branch 'origin/master'
This commit is contained in:
commit
a16584c513
|
@ -9,7 +9,7 @@ import java.util.Map;
|
||||||
|
|
||||||
@Path("baeldung")
|
@Path("baeldung")
|
||||||
@Produces("text/xml")
|
@Produces("text/xml")
|
||||||
public class Baeldung {
|
public class CourseRepository {
|
||||||
private Map<Integer, Course> courses = new HashMap<>();
|
private Map<Integer, Course> courses = new HashMap<>();
|
||||||
|
|
||||||
{
|
{
|
|
@ -7,8 +7,8 @@ import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
|
||||||
public class RestfulServer {
|
public class RestfulServer {
|
||||||
public static void main(String args[]) throws Exception {
|
public static void main(String args[]) throws Exception {
|
||||||
JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
|
JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
|
||||||
factoryBean.setResourceClasses(Baeldung.class);
|
factoryBean.setResourceClasses(CourseRepository.class);
|
||||||
factoryBean.setResourceProvider(new SingletonResourceProvider(new Baeldung()));
|
factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository()));
|
||||||
factoryBean.setAddress("http://localhost:8080/");
|
factoryBean.setAddress("http://localhost:8080/");
|
||||||
Server server = factoryBean.create();
|
Server server = factoryBean.create();
|
||||||
|
|
||||||
|
|
|
@ -162,6 +162,8 @@
|
||||||
<configuration>
|
<configuration>
|
||||||
<excludes>
|
<excludes>
|
||||||
<exclude>**/*IntegrationTest.java</exclude>
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
|
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
|
@ -7,8 +7,7 @@ import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class Pizza {
|
public class Pizza {
|
||||||
|
|
||||||
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses =
|
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses = EnumSet.of(PizzaStatusEnum.DELIVERED);
|
||||||
EnumSet.of(PizzaStatusEnum.DELIVERED);
|
|
||||||
|
|
||||||
private PizzaStatusEnum status;
|
private PizzaStatusEnum status;
|
||||||
|
|
||||||
|
@ -76,9 +75,7 @@ public class Pizza {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
||||||
return pzList.stream().collect(
|
return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
||||||
Collectors.groupingBy(Pizza::getStatus,
|
|
||||||
() -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deliver() {
|
public void deliver() {
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.enums;
|
package com.baeldung.enums;
|
||||||
|
|
||||||
|
|
||||||
public enum PizzaDeliverySystemConfiguration {
|
public enum PizzaDeliverySystemConfiguration {
|
||||||
INSTANCE;
|
INSTANCE;
|
||||||
|
|
||||||
|
|
|
@ -30,8 +30,7 @@ public class CustomRecursiveAction extends RecursiveAction {
|
||||||
|
|
||||||
private Collection<CustomRecursiveAction> createSubtasks() {
|
private Collection<CustomRecursiveAction> createSubtasks() {
|
||||||
|
|
||||||
List<CustomRecursiveAction> subtasks =
|
List<CustomRecursiveAction> subtasks = new ArrayList<>();
|
||||||
new ArrayList<>();
|
|
||||||
|
|
||||||
String partOne = workLoad.substring(0, workLoad.length() / 2);
|
String partOne = workLoad.substring(0, workLoad.length() / 2);
|
||||||
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
|
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.forkjoin;
|
package com.baeldung.forkjoin;
|
||||||
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
@ -23,10 +22,7 @@ public class CustomRecursiveTask extends RecursiveTask<Integer> {
|
||||||
|
|
||||||
if (arr.length > THRESHOLD) {
|
if (arr.length > THRESHOLD) {
|
||||||
|
|
||||||
return ForkJoinTask.invokeAll(createSubtasks())
|
return ForkJoinTask.invokeAll(createSubtasks()).stream().mapToInt(ForkJoinTask::join).sum();
|
||||||
.stream()
|
|
||||||
.mapToInt(ForkJoinTask::join)
|
|
||||||
.sum();
|
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
return processing(arr);
|
return processing(arr);
|
||||||
|
@ -35,17 +31,12 @@ public class CustomRecursiveTask extends RecursiveTask<Integer> {
|
||||||
|
|
||||||
private Collection<CustomRecursiveTask> createSubtasks() {
|
private Collection<CustomRecursiveTask> createSubtasks() {
|
||||||
List<CustomRecursiveTask> dividedTasks = new ArrayList<>();
|
List<CustomRecursiveTask> dividedTasks = new ArrayList<>();
|
||||||
dividedTasks.add(new CustomRecursiveTask(
|
dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, 0, arr.length / 2)));
|
||||||
Arrays.copyOfRange(arr, 0, arr.length / 2)));
|
dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
|
||||||
dividedTasks.add(new CustomRecursiveTask(
|
|
||||||
Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
|
|
||||||
return dividedTasks;
|
return dividedTasks;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Integer processing(int[] arr) {
|
private Integer processing(int[] arr) {
|
||||||
return Arrays.stream(arr)
|
return Arrays.stream(arr).filter(a -> a > 10 && a < 27).map(a -> a * 10).sum();
|
||||||
.filter(a -> a > 10 && a < 27)
|
|
||||||
.map(a -> a * 10)
|
|
||||||
.sum();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.forkjoin.util;
|
package com.baeldung.forkjoin.util;
|
||||||
|
|
||||||
|
|
||||||
import java.util.concurrent.ForkJoinPool;
|
import java.util.concurrent.ForkJoinPool;
|
||||||
|
|
||||||
public class PoolUtil {
|
public class PoolUtil {
|
||||||
|
|
|
@ -0,0 +1,56 @@
|
||||||
|
package com.baeldung.java.networking.cookies;
|
||||||
|
|
||||||
|
import java.net.*;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class PersistentCookieStore implements CookieStore, Runnable {
|
||||||
|
CookieStore store;
|
||||||
|
|
||||||
|
public PersistentCookieStore() {
|
||||||
|
store = new CookieManager().getCookieStore();
|
||||||
|
// deserialize cookies into store
|
||||||
|
Runtime.getRuntime().addShutdownHook(new Thread(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
// serialize cookies to persistent storage
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void add(URI uri, HttpCookie cookie) {
|
||||||
|
store.add(uri, cookie);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<HttpCookie> get(URI uri) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<HttpCookie> getCookies() {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<URI> getURIs() {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean remove(URI uri, HttpCookie cookie) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean removeAll() {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.java.networking.cookies;
|
||||||
|
|
||||||
|
import java.net.*;
|
||||||
|
|
||||||
|
public class ProxyAcceptCookiePolicy implements CookiePolicy {
|
||||||
|
String acceptedProxy;
|
||||||
|
|
||||||
|
public ProxyAcceptCookiePolicy(String acceptedProxy) {
|
||||||
|
this.acceptedProxy = acceptedProxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean shouldAccept(URI uri, HttpCookie cookie) {
|
||||||
|
String host;
|
||||||
|
try {
|
||||||
|
host = InetAddress.getByName(uri.getHost()).getCanonicalHostName();
|
||||||
|
} catch (UnknownHostException e) {
|
||||||
|
host = uri.getHost();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!HttpCookie.domainMatches(acceptedProxy, host)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.java.networking.udp;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.DatagramPacket;
|
||||||
|
import java.net.DatagramSocket;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
|
||||||
|
public class EchoClient {
|
||||||
|
private DatagramSocket socket;
|
||||||
|
private InetAddress address;
|
||||||
|
|
||||||
|
private byte[] buf;
|
||||||
|
|
||||||
|
public EchoClient() {
|
||||||
|
try {
|
||||||
|
socket = new DatagramSocket();
|
||||||
|
address = InetAddress.getByName("localhost");
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public String sendEcho(String msg) {
|
||||||
|
DatagramPacket packet = null;
|
||||||
|
try {
|
||||||
|
buf=msg.getBytes();
|
||||||
|
packet = new DatagramPacket(buf, buf.length, address, 4445);
|
||||||
|
socket.send(packet);
|
||||||
|
packet = new DatagramPacket(buf, buf.length);
|
||||||
|
socket.receive(packet);
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
String received = new String(packet.getData(), 0, packet.getLength());
|
||||||
|
return received;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void close() {
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.java.networking.udp;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.DatagramPacket;
|
||||||
|
import java.net.DatagramSocket;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
|
||||||
|
public class EchoServer extends Thread {
|
||||||
|
|
||||||
|
protected DatagramSocket socket = null;
|
||||||
|
protected boolean running;
|
||||||
|
protected byte[] buf = new byte[256];
|
||||||
|
|
||||||
|
public EchoServer() throws IOException {
|
||||||
|
socket = new DatagramSocket(4445);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
running = true;
|
||||||
|
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
|
||||||
|
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||||
|
socket.receive(packet);
|
||||||
|
InetAddress address = packet.getAddress();
|
||||||
|
int port = packet.getPort();
|
||||||
|
packet = new DatagramPacket(buf, buf.length, address, port);
|
||||||
|
String received = new String(packet.getData(), 0, packet.getLength());
|
||||||
|
if (received.equals("end")) {
|
||||||
|
running = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
socket.send(packet);
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
running = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,15 +1,15 @@
|
||||||
package com.baeldung.java.nio.selector;
|
package com.baeldung.java.nio.selector;
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.InetSocketAddress;
|
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
import java.nio.channels.SelectionKey;
|
|
||||||
import java.nio.channels.Selector;
|
|
||||||
import java.nio.channels.ServerSocketChannel;
|
import java.nio.channels.ServerSocketChannel;
|
||||||
import java.nio.channels.SocketChannel;
|
import java.nio.channels.SocketChannel;
|
||||||
import java.util.Iterator;
|
import java.nio.channels.Selector;
|
||||||
|
import java.nio.channels.SelectionKey;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.io.IOException;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.io.File;
|
||||||
|
|
||||||
public class EchoServer {
|
public class EchoServer {
|
||||||
|
|
||||||
|
@ -49,6 +49,7 @@ public class EchoServer {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static Process start() throws IOException, InterruptedException {
|
public static Process start() throws IOException, InterruptedException {
|
||||||
String javaHome = System.getProperty("java.home");
|
String javaHome = System.getProperty("java.home");
|
||||||
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||||
|
|
|
@ -12,8 +12,7 @@ public class EchoClient {
|
||||||
try {
|
try {
|
||||||
clientSocket = new Socket(ip, port);
|
clientSocket = new Socket(ip, port);
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.out.print(e);
|
System.out.print(e);
|
||||||
}
|
}
|
||||||
|
|
|
@ -42,8 +42,7 @@ public class EchoMultiServer {
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
|
||||||
String inputLine;
|
String inputLine;
|
||||||
while ((inputLine = in.readLine()) != null) {
|
while ((inputLine = in.readLine()) != null) {
|
||||||
if (".".equals(inputLine)) {
|
if (".".equals(inputLine)) {
|
||||||
|
|
|
@ -14,8 +14,7 @@ public class EchoServer {
|
||||||
serverSocket = new ServerSocket(port);
|
serverSocket = new ServerSocket(port);
|
||||||
clientSocket = serverSocket.accept();
|
clientSocket = serverSocket.accept();
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
|
||||||
String inputLine;
|
String inputLine;
|
||||||
while ((inputLine = in.readLine()) != null) {
|
while ((inputLine = in.readLine()) != null) {
|
||||||
if (".".equals(inputLine)) {
|
if (".".equals(inputLine)) {
|
||||||
|
|
|
@ -15,8 +15,7 @@ public class GreetClient {
|
||||||
try {
|
try {
|
||||||
clientSocket = new Socket(ip, port);
|
clientSocket = new Socket(ip, port);
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,14 +9,12 @@ public class GreetServer {
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
|
||||||
|
|
||||||
public void start(int port) {
|
public void start(int port) {
|
||||||
try {
|
try {
|
||||||
serverSocket = new ServerSocket(port);
|
serverSocket = new ServerSocket(port);
|
||||||
clientSocket = serverSocket.accept();
|
clientSocket = serverSocket.accept();
|
||||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||||
in = new BufferedReader(new InputStreamReader(
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||||
clientSocket.getInputStream()));
|
|
||||||
String greeting = in.readLine();
|
String greeting = in.readLine();
|
||||||
if ("hello server".equals(greeting))
|
if ("hello server".equals(greeting))
|
||||||
out.println("hello client");
|
out.println("hello client");
|
||||||
|
@ -39,6 +37,7 @@ public class GreetServer {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
GreetServer server = new GreetServer();
|
GreetServer server = new GreetServer();
|
||||||
server.start(6666);
|
server.start(6666);
|
||||||
|
|
|
@ -44,7 +44,6 @@ public class Product {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static Stream<String> streamOf(List<String> list) {
|
public static Stream<String> streamOf(List<String> list) {
|
||||||
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
|
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,9 +14,7 @@ public class CountingTask extends RecursiveTask<Integer> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected Integer compute() {
|
protected Integer compute() {
|
||||||
return node.value + node.children.stream()
|
return node.value + node.children.stream().map(childNode -> new CountingTask(childNode).fork()).collect(Collectors.summingInt(ForkJoinTask::join));
|
||||||
.map(childNode -> new CountingTask(childNode).fork())
|
|
||||||
.collect(Collectors.summingInt(ForkJoinTask::join));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,7 +6,7 @@ import org.junit.Test;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ThreadLocalRandom;
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
public class RandomListElementTest {
|
public class RandomListElementUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
|
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
|
|
@ -1,11 +1,12 @@
|
||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import com.google.common.primitives.Ints;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class StringToIntOrIntegerTest {
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.common.primitives.Ints;
|
||||||
|
|
||||||
|
public class StringToIntOrIntegerUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenParsingInt_shouldConvertToInt() {
|
public void givenString_whenParsingInt_shouldConvertToInt() {
|
||||||
|
@ -16,7 +17,6 @@ public class StringToIntOrIntegerTest {
|
||||||
assertThat(result).isEqualTo(42);
|
assertThat(result).isEqualTo(42);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
|
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
|
||||||
String givenString = "42";
|
String givenString = "42";
|
|
@ -42,192 +42,137 @@ public class Java8CollectorsTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||||
final List<String> result = givenList.stream()
|
final List<String> result = givenList.stream().collect(toList());
|
||||||
.collect(toList());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList);
|
||||||
.containsAll(givenList);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||||
final Set<String> result = givenList.stream()
|
final Set<String> result = givenList.stream().collect(toSet());
|
||||||
.collect(toSet());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList);
|
||||||
.containsAll(givenList);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||||
final List<String> result = givenList.stream()
|
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||||
.collect(toCollection(LinkedList::new));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(LinkedList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||||
assertThatThrownBy(() -> {
|
assertThatThrownBy(() -> {
|
||||||
givenList.stream()
|
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||||
.collect(toCollection(ImmutableList::of));
|
|
||||||
}).isInstanceOf(UnsupportedOperationException.class);
|
}).isInstanceOf(UnsupportedOperationException.class);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||||
final Map<String, Integer> result = givenList.stream()
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||||
.collect(toMap(Function.identity(), String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||||
final Map<String, Integer> result = givenList.stream()
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||||
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||||
final List<String> result = givenList.stream()
|
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(ImmutableList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoining_shouldJoin() throws Exception {
|
public void whenJoining_shouldJoin() throws Exception {
|
||||||
final String result = givenList.stream()
|
final String result = givenList.stream().collect(joining());
|
||||||
.collect(joining());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo("abbcccdd");
|
||||||
.isEqualTo("abbcccdd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||||
final String result = givenList.stream()
|
final String result = givenList.stream().collect(joining(" "));
|
||||||
.collect(joining(" "));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo("a bb ccc dd");
|
||||||
.isEqualTo("a bb ccc dd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||||
final String result = givenList.stream()
|
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||||
.collect(joining(" ", "PRE-", "-POST"));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||||
.isEqualTo("PRE-a bb ccc dd-POST");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||||
final Map<Boolean, List<String>> result = givenList.stream()
|
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||||
.collect(partitioningBy(s -> s.length() > 2));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||||
.containsKeys(true, false)
|
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||||
.satisfies(booleanListMap -> {
|
|
||||||
assertThat(booleanListMap.get(true))
|
|
||||||
.contains("ccc");
|
|
||||||
|
|
||||||
assertThat(booleanListMap.get(false))
|
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||||
.contains("a", "bb", "dd");
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCounting_shouldCount() throws Exception {
|
public void whenCounting_shouldCount() throws Exception {
|
||||||
final Long result = givenList.stream()
|
final Long result = givenList.stream().collect(counting());
|
||||||
.collect(counting());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo(4);
|
||||||
.isEqualTo(4);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||||
final DoubleSummaryStatistics result = givenList.stream()
|
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||||
.collect(summarizingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result.getAverage())
|
assertThat(result.getAverage()).isEqualTo(2);
|
||||||
.isEqualTo(2);
|
assertThat(result.getCount()).isEqualTo(4);
|
||||||
assertThat(result.getCount())
|
assertThat(result.getMax()).isEqualTo(3);
|
||||||
.isEqualTo(4);
|
assertThat(result.getMin()).isEqualTo(1);
|
||||||
assertThat(result.getMax())
|
assertThat(result.getSum()).isEqualTo(8);
|
||||||
.isEqualTo(3);
|
|
||||||
assertThat(result.getMin())
|
|
||||||
.isEqualTo(1);
|
|
||||||
assertThat(result.getSum())
|
|
||||||
.isEqualTo(8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAveraging_shouldAverage() throws Exception {
|
public void whenAveraging_shouldAverage() throws Exception {
|
||||||
final Double result = givenList.stream()
|
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||||
.collect(averagingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo(2);
|
||||||
.isEqualTo(2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSumming_shouldSum() throws Exception {
|
public void whenSumming_shouldSum() throws Exception {
|
||||||
final Double result = givenList.stream()
|
final Double result = givenList.stream().collect(summingDouble(String::length));
|
||||||
.collect(summingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isEqualTo(8);
|
||||||
.isEqualTo(8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||||
final Optional<String> result = givenList.stream()
|
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||||
.collect(maxBy(Comparator.naturalOrder()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isPresent().hasValue("dd");
|
||||||
.isPresent()
|
|
||||||
.hasValue("dd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||||
final Map<Integer, Set<String>> result = givenList.stream()
|
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||||
.collect(groupingBy(String::length, toSet()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||||
.containsEntry(1, newHashSet("a"))
|
|
||||||
.containsEntry(2, newHashSet("bb", "dd"))
|
|
||||||
.containsEntry(3, newHashSet("ccc"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||||
final ImmutableSet<String> result = givenList.stream()
|
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||||
.collect(toImmutableSet());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
|
||||||
.isInstanceOf(ImmutableSet.class)
|
|
||||||
.contains("a", "bb", "ccc", "dd");
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,24 +1,26 @@
|
||||||
package com.baeldung.completablefuture;
|
package com.baeldung.completablefuture;
|
||||||
|
|
||||||
import java.util.concurrent.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.concurrent.CancellationException;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
public class CompletableFutureUnitTest {
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
public class CompletableFutureTest {
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
|
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
|
||||||
|
|
||||||
Future<String> completableFuture = calculateAsync();
|
Future<String> completableFuture = calculateAsync();
|
||||||
|
|
||||||
String result = completableFuture.get();
|
String result = completableFuture.get();
|
||||||
assertEquals("Hello", result);
|
assertEquals("Hello", result);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Future<String> calculateAsync() throws InterruptedException {
|
public Future<String> calculateAsync() throws InterruptedException {
|
||||||
|
@ -35,15 +37,12 @@ public class CompletableFutureTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException {
|
public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException {
|
||||||
|
|
||||||
Future<String> completableFuture = CompletableFuture.completedFuture("Hello");
|
Future<String> completableFuture = CompletableFuture.completedFuture("Hello");
|
||||||
|
|
||||||
String result = completableFuture.get();
|
String result = completableFuture.get();
|
||||||
assertEquals("Hello", result);
|
assertEquals("Hello", result);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
|
||||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||||
|
|
||||||
|
@ -56,90 +55,67 @@ public class CompletableFutureTest {
|
||||||
return completableFuture;
|
return completableFuture;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test(expected = CancellationException.class)
|
@Test(expected = CancellationException.class)
|
||||||
public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException {
|
public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
Future<String> future = calculateAsyncWithCancellation();
|
Future<String> future = calculateAsyncWithCancellation();
|
||||||
future.get();
|
future.get();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
|
public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
|
|
||||||
assertEquals("Hello", future.get());
|
assertEquals("Hello", future.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
|
|
||||||
CompletableFuture<Void> future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s));
|
CompletableFuture<Void> future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s));
|
||||||
|
|
||||||
future.get();
|
future.get();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
|
|
||||||
CompletableFuture<Void> future = completableFuture.thenRun(() -> System.out.println("Computation finished."));
|
CompletableFuture<Void> future = completableFuture.thenRun(() -> System.out.println("Computation finished."));
|
||||||
|
|
||||||
future.get();
|
future.get();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
|
|
||||||
CompletableFuture<String> future = completableFuture.thenApply(s -> s + " World");
|
CompletableFuture<String> future = completableFuture.thenApply(s -> s + " World");
|
||||||
|
|
||||||
assertEquals("Hello World", future.get());
|
assertEquals("Hello World", future.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
|
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
|
||||||
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
|
|
||||||
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
|
|
||||||
|
|
||||||
assertEquals("Hello World", completableFuture.get());
|
assertEquals("Hello World", completableFuture.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
||||||
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
|
|
||||||
.thenCombine(CompletableFuture.supplyAsync(() -> " World"),
|
|
||||||
(s1, s2) -> s1 + s2);
|
|
||||||
|
|
||||||
assertEquals("Hello World", completableFuture.get());
|
assertEquals("Hello World", completableFuture.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
|
||||||
|
CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> System.out.println(s1 + s2));
|
||||||
CompletableFuture.supplyAsync(() -> "Hello")
|
|
||||||
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"),
|
|
||||||
(s1, s2) -> System.out.println(s1 + s2));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException {
|
public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful");
|
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful");
|
||||||
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World");
|
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World");
|
||||||
|
@ -154,17 +130,13 @@ public class CompletableFutureTest {
|
||||||
assertTrue(future2.isDone());
|
assertTrue(future2.isDone());
|
||||||
assertTrue(future3.isDone());
|
assertTrue(future3.isDone());
|
||||||
|
|
||||||
String combined = Stream.of(future1, future2, future3)
|
String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" "));
|
||||||
.map(CompletableFuture::join)
|
|
||||||
.collect(Collectors.joining(" "));
|
|
||||||
|
|
||||||
assertEquals("Hello Beautiful World", combined);
|
assertEquals("Hello Beautiful World", combined);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException {
|
public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
String name = null;
|
String name = null;
|
||||||
|
|
||||||
// ...
|
// ...
|
||||||
|
@ -177,12 +149,10 @@ public class CompletableFutureTest {
|
||||||
}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
|
}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
|
||||||
|
|
||||||
assertEquals("Hello, Stranger!", completableFuture.get());
|
assertEquals("Hello, Stranger!", completableFuture.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected = ExecutionException.class)
|
@Test(expected = ExecutionException.class)
|
||||||
public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException {
|
public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||||
|
|
||||||
// ...
|
// ...
|
||||||
|
@ -192,18 +162,15 @@ public class CompletableFutureTest {
|
||||||
// ...
|
// ...
|
||||||
|
|
||||||
completableFuture.get();
|
completableFuture.get();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||||
|
|
||||||
CompletableFuture<String> future = completableFuture.thenApplyAsync(s -> s + " World");
|
CompletableFuture<String> future = completableFuture.thenApplyAsync(s -> s + " World");
|
||||||
|
|
||||||
assertEquals("Hello World", future.get());
|
assertEquals("Hello World", future.get());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -14,7 +14,7 @@ import java.time.temporal.ChronoUnit;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class JavaUtilTimeTest {
|
public class JavaUtilTimeUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void currentTime() {
|
public void currentTime() {
|
|
@ -1,7 +1,8 @@
|
||||||
package com.baeldung.functionalinterface;
|
package com.baeldung.functionalinterface;
|
||||||
|
|
||||||
import com.google.common.util.concurrent.Uninterruptibles;
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
@ -13,38 +14,28 @@ import java.util.function.Supplier;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class FunctionalInterfaceTest {
|
import com.google.common.util.concurrent.Uninterruptibles;
|
||||||
|
|
||||||
|
public class FunctionalInterfaceUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
||||||
|
|
||||||
Map<String, Integer> nameMap = new HashMap<>();
|
Map<String, Integer> nameMap = new HashMap<>();
|
||||||
Integer value = nameMap.computeIfAbsent("John", s -> s.length());
|
Integer value = nameMap.computeIfAbsent("John", s -> s.length());
|
||||||
|
|
||||||
assertEquals(new Integer(4), nameMap.get("John"));
|
assertEquals(new Integer(4), nameMap.get("John"));
|
||||||
assertEquals(new Integer(4), value);
|
assertEquals(new Integer(4), value);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
|
||||||
|
|
||||||
Map<String, Integer> nameMap = new HashMap<>();
|
Map<String, Integer> nameMap = new HashMap<>();
|
||||||
Integer value = nameMap.computeIfAbsent("John", String::length);
|
Integer value = nameMap.computeIfAbsent("John", String::length);
|
||||||
|
|
||||||
assertEquals(new Integer(4), nameMap.get("John"));
|
assertEquals(new Integer(4), nameMap.get("John"));
|
||||||
assertEquals(new Integer(4), value);
|
assertEquals(new Integer(4), value);
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public byte[] transformArray(short[] array, ShortToByteFunction function) {
|
|
||||||
byte[] transformedArray = new byte[array.length];
|
|
||||||
for (int i = 0; i < array.length; i++) {
|
|
||||||
transformedArray[i] = function.applyAsByte(array[i]);
|
|
||||||
}
|
|
||||||
return transformedArray;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -60,7 +51,6 @@ public class FunctionalInterfaceTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() {
|
public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() {
|
||||||
|
|
||||||
Map<String, Integer> salaries = new HashMap<>();
|
Map<String, Integer> salaries = new HashMap<>();
|
||||||
salaries.put("John", 40000);
|
salaries.put("John", 40000);
|
||||||
salaries.put("Freddy", 30000);
|
salaries.put("Freddy", 30000);
|
||||||
|
@ -71,16 +61,12 @@ public class FunctionalInterfaceTest {
|
||||||
assertEquals(new Integer(50000), salaries.get("John"));
|
assertEquals(new Integer(50000), salaries.get("John"));
|
||||||
assertEquals(new Integer(30000), salaries.get("Freddy"));
|
assertEquals(new Integer(30000), salaries.get("Freddy"));
|
||||||
assertEquals(new Integer(60000), salaries.get("Samuel"));
|
assertEquals(new Integer(60000), salaries.get("Samuel"));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() {
|
public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() {
|
||||||
|
|
||||||
Thread thread = new Thread(() -> System.out.println("Hello From Another Thread"));
|
Thread thread = new Thread(() -> System.out.println("Hello From Another Thread"));
|
||||||
thread.start();
|
thread.start();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -95,55 +81,44 @@ public class FunctionalInterfaceTest {
|
||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
|
|
||||||
List<Integer> fibonacci5 = fibonacci.limit(5)
|
List<Integer> fibonacci5 = fibonacci.limit(5).collect(Collectors.toList());
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(new Integer(1), fibonacci5.get(0));
|
assertEquals(new Integer(1), fibonacci5.get(0));
|
||||||
assertEquals(new Integer(1), fibonacci5.get(1));
|
assertEquals(new Integer(1), fibonacci5.get(1));
|
||||||
assertEquals(new Integer(2), fibonacci5.get(2));
|
assertEquals(new Integer(2), fibonacci5.get(2));
|
||||||
assertEquals(new Integer(3), fibonacci5.get(3));
|
assertEquals(new Integer(3), fibonacci5.get(3));
|
||||||
assertEquals(new Integer(5), fibonacci5.get(4));
|
assertEquals(new Integer(5), fibonacci5.get(4));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
|
public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
|
||||||
|
|
||||||
List<String> names = Arrays.asList("John", "Freddy", "Samuel");
|
List<String> names = Arrays.asList("John", "Freddy", "Samuel");
|
||||||
names.forEach(name -> System.out.println("Hello, " + name));
|
names.forEach(name -> System.out.println("Hello, " + name));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() {
|
public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() {
|
||||||
|
|
||||||
Map<String, Integer> ages = new HashMap<>();
|
Map<String, Integer> ages = new HashMap<>();
|
||||||
ages.put("John", 25);
|
ages.put("John", 25);
|
||||||
ages.put("Freddy", 24);
|
ages.put("Freddy", 24);
|
||||||
ages.put("Samuel", 30);
|
ages.put("Samuel", 30);
|
||||||
|
|
||||||
ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));
|
ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
|
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
|
||||||
|
|
||||||
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
|
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
|
||||||
|
|
||||||
List<String> namesWithA = names.stream()
|
List<String> namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList());
|
||||||
.filter(name -> name.startsWith("A"))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(2, namesWithA.size());
|
assertEquals(2, namesWithA.size());
|
||||||
assertTrue(namesWithA.contains("Angela"));
|
assertTrue(namesWithA.contains("Angela"));
|
||||||
assertTrue(namesWithA.contains("Aaron"));
|
assertTrue(namesWithA.contains("Aaron"));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() {
|
public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() {
|
||||||
|
|
||||||
List<String> names = Arrays.asList("bob", "josh", "megan");
|
List<String> names = Arrays.asList("bob", "josh", "megan");
|
||||||
|
|
||||||
names.replaceAll(String::toUpperCase);
|
names.replaceAll(String::toUpperCase);
|
||||||
|
@ -151,7 +126,6 @@ public class FunctionalInterfaceTest {
|
||||||
assertEquals("BOB", names.get(0));
|
assertEquals("BOB", names.get(0));
|
||||||
assertEquals("JOSH", names.get(1));
|
assertEquals("JOSH", names.get(1));
|
||||||
assertEquals("MEGAN", names.get(2));
|
assertEquals("MEGAN", names.get(2));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -159,8 +133,7 @@ public class FunctionalInterfaceTest {
|
||||||
|
|
||||||
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
|
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
|
||||||
|
|
||||||
int sum = values.stream()
|
int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2);
|
||||||
.reduce(0, (i1, i2) -> i1 + i2);
|
|
||||||
|
|
||||||
assertEquals(37, sum);
|
assertEquals(37, sum);
|
||||||
|
|
||||||
|
@ -178,10 +151,6 @@ public class FunctionalInterfaceTest {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public double squareLazy(Supplier<Double> lazyValue) {
|
|
||||||
return Math.pow(lazyValue.get(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
|
public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
|
||||||
|
|
||||||
|
@ -196,4 +165,18 @@ public class FunctionalInterfaceTest {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
|
||||||
|
public double squareLazy(Supplier<Double> lazyValue) {
|
||||||
|
return Math.pow(lazyValue.get(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] transformArray(short[] array, ShortToByteFunction function) {
|
||||||
|
byte[] transformedArray = new byte[array.length];
|
||||||
|
for (int i = 0; i < array.length; i++) {
|
||||||
|
transformedArray[i] = function.applyAsByte(array[i]);
|
||||||
|
}
|
||||||
|
return transformedArray;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.java.networking.udp;
|
||||||
|
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
|
||||||
|
public class UDPTest {
|
||||||
|
private EchoClient client;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws IOException {
|
||||||
|
new EchoServer().start();
|
||||||
|
client = new EchoClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCanSendAndReceivePacket_thenCorrect1() {
|
||||||
|
String echo = client.sendEcho("hello server");
|
||||||
|
assertEquals("hello server", echo);
|
||||||
|
echo = client.sendEcho("server is working");
|
||||||
|
assertFalse(echo.equals("hello server"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() {
|
||||||
|
stopEchoServer();
|
||||||
|
client.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stopEchoServer() {
|
||||||
|
client.sendEcho("end");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,104 @@
|
||||||
|
package com.baeldung.java.networking.url;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class UrlTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
|
||||||
|
URL url = new URL("http://baeldung.com");
|
||||||
|
assertEquals("http", url.getProtocol());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException {
|
||||||
|
URL url = new URL("http://baeldung.com");
|
||||||
|
assertEquals("baeldung.com", url.getHost());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException {
|
||||||
|
URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
|
||||||
|
assertEquals("/articles?topic=java&version=8", url.getFile());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException {
|
||||||
|
URL url = new URL("http://baeldung.com/guidelines.txt");
|
||||||
|
assertEquals("/guidelines.txt", url.getFile());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException {
|
||||||
|
URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
|
||||||
|
assertEquals("/articles", url.getPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException {
|
||||||
|
URL url = new URL("http://baeldung.com/articles?topic=java");
|
||||||
|
assertEquals("topic=java", url.getQuery());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException {
|
||||||
|
URL url = new URL("http://baeldung.com");
|
||||||
|
assertEquals(-1, url.getPort());
|
||||||
|
assertEquals(80, url.getDefaultPort());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException {
|
||||||
|
URL url = new URL("http://baeldung.com:8090");
|
||||||
|
assertEquals(8090, url.getPort());
|
||||||
|
assertEquals(80, url.getDefaultPort());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException {
|
||||||
|
URL baseUrl = new URL("http://baeldung.com");
|
||||||
|
URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets");
|
||||||
|
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException {
|
||||||
|
URL baseUrl = new URL("http://baeldung.com");
|
||||||
|
URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets");
|
||||||
|
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
|
||||||
|
String protocol = "http";
|
||||||
|
String host = "baeldung.com";
|
||||||
|
String file = "/guidelines.txt";
|
||||||
|
URL url = new URL(protocol, host, file);
|
||||||
|
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException {
|
||||||
|
String protocol = "http";
|
||||||
|
String host = "baeldung.com";
|
||||||
|
String file = "/articles?topic=java&version=8";
|
||||||
|
URL url = new URL(protocol, host, file);
|
||||||
|
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
|
||||||
|
String protocol = "http";
|
||||||
|
String host = "baeldung.com";
|
||||||
|
int port = 9000;
|
||||||
|
String file = "/guidelines.txt";
|
||||||
|
URL url = new URL(protocol, host, port, file);
|
||||||
|
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -16,6 +16,7 @@ public class EchoTest {
|
||||||
String resp2 = client.sendMessage("world");
|
String resp2 = client.sendMessage("world");
|
||||||
assertEquals("hello", resp1);
|
assertEquals("hello", resp1);
|
||||||
assertEquals("world", resp2);
|
assertEquals("world", resp2);
|
||||||
|
|
||||||
process.destroy();
|
process.destroy();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,7 +11,7 @@ import java.util.List;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class ReflectionTest {
|
public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
|
public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
|
||||||
|
@ -20,8 +20,7 @@ public class ReflectionTest {
|
||||||
|
|
||||||
List<String> actualFieldNames = getFieldNames(fields);
|
List<String> actualFieldNames = getFieldNames(fields);
|
||||||
|
|
||||||
assertTrue(Arrays.asList("name", "age")
|
assertTrue(Arrays.asList("name", "age").containsAll(actualFieldNames));
|
||||||
.containsAll(actualFieldNames));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -35,8 +34,7 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassName_whenCreatesObject_thenCorrect()
|
public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat");
|
Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
|
|
||||||
assertEquals("Goat", clazz.getSimpleName());
|
assertEquals("Goat", clazz.getSimpleName());
|
||||||
|
@ -45,8 +43,7 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenRecognisesModifiers_thenCorrect()
|
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
int goatMods = goatClass.getModifiers();
|
int goatMods = goatClass.getModifiers();
|
||||||
|
@ -80,8 +77,7 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsImplementedInterfaces_thenCorrect()
|
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
Class<?>[] goatInterfaces = goatClass.getInterfaces();
|
Class<?>[] goatInterfaces = goatClass.getInterfaces();
|
||||||
|
@ -94,8 +90,7 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsConstructor_thenCorrect()
|
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
Constructor<?>[] constructors = goatClass.getConstructors();
|
Constructor<?>[] constructors = goatClass.getConstructors();
|
||||||
|
|
||||||
|
@ -104,8 +99,7 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsFields_thenCorrect()
|
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
Field[] fields = animalClass.getDeclaredFields();
|
Field[] fields = animalClass.getDeclaredFields();
|
||||||
|
|
||||||
|
@ -116,20 +110,17 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsMethods_thenCorrect()
|
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
Method[] methods = animalClass.getDeclaredMethods();
|
Method[] methods = animalClass.getDeclaredMethods();
|
||||||
List<String> actualMethods = getMethodNames(methods);
|
List<String> actualMethods = getMethodNames(methods);
|
||||||
|
|
||||||
assertEquals(4, actualMethods.size());
|
assertEquals(4, actualMethods.size());
|
||||||
assertTrue(actualMethods.containsAll(Arrays.asList("getName",
|
assertTrue(actualMethods.containsAll(Arrays.asList("getName", "setName", "getSound")));
|
||||||
"setName", "getSound")));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsAllConstructors_thenCorrect()
|
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Constructor<?>[] constructors = birdClass.getConstructors();
|
Constructor<?>[] constructors = birdClass.getConstructors();
|
||||||
|
|
||||||
|
@ -137,24 +128,20 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect()
|
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Constructor<?> cons1 = birdClass.getConstructor();
|
Constructor<?> cons1 = birdClass.getConstructor();
|
||||||
Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
||||||
Constructor<?> cons3 = birdClass.getConstructor(String.class,
|
Constructor<?> cons3 = birdClass.getConstructor(String.class, boolean.class);
|
||||||
boolean.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect()
|
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
|
|
||||||
Constructor<?> cons1 = birdClass.getConstructor();
|
Constructor<?> cons1 = birdClass.getConstructor();
|
||||||
Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
||||||
Constructor<?> cons3 = birdClass.getConstructor(String.class,
|
Constructor<?> cons3 = birdClass.getConstructor(String.class, boolean.class);
|
||||||
boolean.class);
|
|
||||||
|
|
||||||
Bird bird1 = (Bird) cons1.newInstance();
|
Bird bird1 = (Bird) cons1.newInstance();
|
||||||
Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
|
Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
|
||||||
|
@ -168,8 +155,7 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsPublicFields_thenCorrect()
|
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Field[] fields = birdClass.getFields();
|
Field[] fields = birdClass.getFields();
|
||||||
assertEquals(1, fields.length);
|
assertEquals(1, fields.length);
|
||||||
|
@ -178,8 +164,7 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsPublicFieldByName_thenCorrect()
|
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Field field = birdClass.getField("CATEGORY");
|
Field field = birdClass.getField("CATEGORY");
|
||||||
assertEquals("CATEGORY", field.getName());
|
assertEquals("CATEGORY", field.getName());
|
||||||
|
@ -187,8 +172,7 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsDeclaredFields_thenCorrect()
|
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Field[] fields = birdClass.getDeclaredFields();
|
Field[] fields = birdClass.getDeclaredFields();
|
||||||
assertEquals(1, fields.length);
|
assertEquals(1, fields.length);
|
||||||
|
@ -196,8 +180,7 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsFieldsByName_thenCorrect()
|
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Field field = birdClass.getDeclaredField("walks");
|
Field field = birdClass.getDeclaredField("walks");
|
||||||
assertEquals("walks", field.getName());
|
assertEquals("walks", field.getName());
|
||||||
|
@ -205,17 +188,14 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassField_whenGetsType_thenCorrect()
|
public void givenClassField_whenGetsType_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
|
||||||
Field field = Class.forName("com.baeldung.java.reflection.Bird")
|
|
||||||
.getDeclaredField("walks");
|
|
||||||
Class<?> fieldClass = field.getType();
|
Class<?> fieldClass = field.getType();
|
||||||
assertEquals("boolean", fieldClass.getSimpleName());
|
assertEquals("boolean", fieldClass.getSimpleName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassField_whenSetsAndGetsValue_thenCorrect()
|
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Bird bird = (Bird) birdClass.newInstance();
|
Bird bird = (Bird) birdClass.newInstance();
|
||||||
Field field = birdClass.getDeclaredField("walks");
|
Field field = birdClass.getDeclaredField("walks");
|
||||||
|
@ -232,8 +212,7 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect()
|
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Field field = birdClass.getField("CATEGORY");
|
Field field = birdClass.getField("CATEGORY");
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
|
@ -242,21 +221,17 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsAllPublicMethods_thenCorrect()
|
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Method[] methods = birdClass.getMethods();
|
Method[] methods = birdClass.getMethods();
|
||||||
List<String> methodNames = getMethodNames(methods);
|
List<String> methodNames = getMethodNames(methods);
|
||||||
|
|
||||||
assertTrue(methodNames.containsAll(Arrays
|
assertTrue(methodNames.containsAll(Arrays.asList("equals", "notifyAll", "hashCode", "walks", "eats", "toString")));
|
||||||
.asList("equals", "notifyAll", "hashCode",
|
|
||||||
"walks", "eats", "toString")));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect()
|
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
|
||||||
throws ClassNotFoundException {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
|
List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
|
||||||
|
|
||||||
|
@ -269,12 +244,10 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenMethodName_whenGetsMethod_thenCorrect()
|
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Method walksMethod = birdClass.getDeclaredMethod("walks");
|
Method walksMethod = birdClass.getDeclaredMethod("walks");
|
||||||
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks",
|
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
||||||
boolean.class);
|
|
||||||
|
|
||||||
assertFalse(walksMethod.isAccessible());
|
assertFalse(walksMethod.isAccessible());
|
||||||
assertFalse(setWalksMethod.isAccessible());
|
assertFalse(setWalksMethod.isAccessible());
|
||||||
|
@ -288,12 +261,10 @@ public class ReflectionTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenMethod_whenInvokes_thenCorrect()
|
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Bird bird = (Bird) birdClass.newInstance();
|
Bird bird = (Bird) birdClass.newInstance();
|
||||||
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks",
|
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
||||||
boolean.class);
|
|
||||||
Method walksMethod = birdClass.getDeclaredMethod("walks");
|
Method walksMethod = birdClass.getDeclaredMethod("walks");
|
||||||
boolean walks = (boolean) walksMethod.invoke(bird);
|
boolean walks = (boolean) walksMethod.invoke(bird);
|
||||||
|
|
|
@ -7,7 +7,7 @@ import java.util.regex.Pattern;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class RegexTest {
|
public class RegexUnitTest {
|
||||||
private static Pattern pattern;
|
private static Pattern pattern;
|
||||||
private static Matcher matcher;
|
private static Matcher matcher;
|
||||||
|
|
||||||
|
@ -499,4 +499,3 @@ public class RegexTest {
|
||||||
return matches;
|
return matches;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,8 +7,7 @@ import java.io.File;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class ScreenshotIntegrationTest {
|
||||||
public class ScreenshotTest {
|
|
||||||
|
|
||||||
private Screenshot screenshot = new Screenshot("Screenshot.jpg");
|
private Screenshot screenshot = new Screenshot("Screenshot.jpg");
|
||||||
private File file = new File("Screenshot.jpg");
|
private File file = new File("Screenshot.jpg");
|
|
@ -9,7 +9,7 @@ import java.util.concurrent.Executors;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class GreetServerTest {
|
public class GreetServerIntegrationTest {
|
||||||
|
|
||||||
private GreetClient client;
|
private GreetClient client;
|
||||||
|
|
|
@ -3,7 +3,7 @@ package org.baeldung.equalshashcode.entities;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class PrimitiveClassTest {
|
public class PrimitiveClassUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testTwoEqualsObjects() {
|
public void testTwoEqualsObjects() {
|
|
@ -5,11 +5,10 @@ import java.awt.Color;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class SquareClassTest {
|
public class SquareClassUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testEqualsAndHashcodes() {
|
public void testEqualsAndHashcodes() {
|
||||||
|
|
||||||
Square aObject = new Square(10, Color.BLUE);
|
Square aObject = new Square(10, Color.BLUE);
|
||||||
Square bObject = new Square(10, Color.BLUE);
|
Square bObject = new Square(10, Color.BLUE);
|
||||||
|
|
|
@ -14,7 +14,7 @@ import org.slf4j.LoggerFactory;
|
||||||
import com.google.common.base.Charsets;
|
import com.google.common.base.Charsets;
|
||||||
import com.google.common.io.Files;
|
import com.google.common.io.Files;
|
||||||
|
|
||||||
public class JavaIoIntegrationTest {
|
public class JavaIoUnitTest {
|
||||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||||
|
|
||||||
// tests - iterate lines in a file
|
// tests - iterate lines in a file
|
|
@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class JavaTimerUnitTest {
|
public class JavaTimerLongRunningUnitTest {
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
|
@ -25,12 +25,9 @@ public class ArraysJoinAndSplitJUnitTest {
|
||||||
|
|
||||||
System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length);
|
System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length);
|
||||||
|
|
||||||
Assert.assertArrayEquals(toppings,
|
Assert.assertArrayEquals(toppings, new String[] { "Marinara", "Olive Oil", "Mozzarella", "Feta", "Parmesan", "Olives", "Spinach", "Green Peppers" });
|
||||||
new String[]{"Marinara", "Olive Oil", "Mozzarella", "Feta",
|
|
||||||
"Parmesan", "Olives", "Spinach", "Green Peppers"});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() {
|
public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() {
|
||||||
int ordersHalved = (customers.length / 2) + (customers.length % 2);
|
int ordersHalved = (customers.length / 2) + (customers.length % 2);
|
||||||
|
|
|
@ -18,10 +18,7 @@ public class ArrayListTest {
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
public void setUp() {
|
||||||
List<String> list = LongStream.range(0, 16)
|
List<String> list = LongStream.range(0, 16).boxed().map(Long::toHexString).collect(toCollection(ArrayList::new));
|
||||||
.boxed()
|
|
||||||
.map(Long::toHexString)
|
|
||||||
.collect(toCollection(ArrayList::new));
|
|
||||||
stringsToSearch = new ArrayList<>(list);
|
stringsToSearch = new ArrayList<>(list);
|
||||||
stringsToSearch.addAll(list);
|
stringsToSearch.addAll(list);
|
||||||
}
|
}
|
||||||
|
@ -34,8 +31,7 @@ public class ArrayListTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() {
|
public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() {
|
||||||
Collection<Integer> numbers =
|
Collection<Integer> numbers = IntStream.range(0, 10).boxed().collect(toSet());
|
||||||
IntStream.range(0, 10).boxed().collect(toSet());
|
|
||||||
|
|
||||||
List<Integer> list = new ArrayList<>(numbers);
|
List<Integer> list = new ArrayList<>(numbers);
|
||||||
assertEquals(10, list.size());
|
assertEquals(10, list.size());
|
||||||
|
@ -56,8 +52,7 @@ public class ArrayListTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenCollection_whenAddToArrayList_thenIsAdded() {
|
public void givenCollection_whenAddToArrayList_thenIsAdded() {
|
||||||
List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
|
List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
|
||||||
LongStream.range(4, 10).boxed()
|
LongStream.range(4, 10).boxed().collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys)));
|
||||||
.collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys)));
|
|
||||||
|
|
||||||
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list));
|
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list));
|
||||||
}
|
}
|
||||||
|
@ -88,10 +83,7 @@ public class ArrayListTest {
|
||||||
public void givenPredicate_whenIterateArrayList_thenFindAllElementsSatisfyingPredicate() {
|
public void givenPredicate_whenIterateArrayList_thenFindAllElementsSatisfyingPredicate() {
|
||||||
Set<String> matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9"));
|
Set<String> matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9"));
|
||||||
|
|
||||||
List<String> result = stringsToSearch
|
List<String> result = stringsToSearch.stream().filter(matchingStrings::contains).collect(toCollection(ArrayList::new));
|
||||||
.stream()
|
|
||||||
.filter(matchingStrings::contains)
|
|
||||||
.collect(toCollection(ArrayList::new));
|
|
||||||
|
|
||||||
assertEquals(6, result.size());
|
assertEquals(6, result.size());
|
||||||
}
|
}
|
||||||
|
@ -131,8 +123,7 @@ public class ArrayListTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() {
|
public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() {
|
||||||
Set<String> matchingStrings
|
Set<String> matchingStrings = Sets.newHashSet("a", "b", "c", "d", "e", "f");
|
||||||
= Sets.newHashSet("a", "b", "c", "d", "e", "f");
|
|
||||||
|
|
||||||
Iterator<String> it = stringsToSearch.iterator();
|
Iterator<String> it = stringsToSearch.iterator();
|
||||||
while (it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
|
|
|
@ -1,21 +1,21 @@
|
||||||
package org.baeldung.java.enums;
|
package org.baeldung.java.enums;
|
||||||
|
|
||||||
|
import static junit.framework.TestCase.assertTrue;
|
||||||
import com.baeldung.enums.Pizza;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.EnumMap;
|
import java.util.EnumMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import static junit.framework.TestCase.assertTrue;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.enums.Pizza;
|
||||||
|
|
||||||
|
public class PizzaUnitTest {
|
||||||
|
|
||||||
public class PizzaTest {
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPizaOrder_whenReady_thenDeliverable() {
|
public void givenPizaOrder_whenReady_thenDeliverable() {
|
||||||
Pizza testPz = new Pizza();
|
Pizza testPz = new Pizza();
|
||||||
testPz.setStatus(Pizza.PizzaStatus.READY);
|
testPz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||||
assertTrue(testPz.isDeliverable());
|
assertTrue(testPz.isDeliverable());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -23,16 +23,16 @@ public class PizzaTest {
|
||||||
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
|
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
|
||||||
List<Pizza> pzList = new ArrayList<>();
|
List<Pizza> pzList = new ArrayList<>();
|
||||||
Pizza pz1 = new Pizza();
|
Pizza pz1 = new Pizza();
|
||||||
pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
|
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
|
||||||
|
|
||||||
Pizza pz2 = new Pizza();
|
Pizza pz2 = new Pizza();
|
||||||
pz2.setStatus(Pizza.PizzaStatus.ORDERED);
|
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||||
|
|
||||||
Pizza pz3 = new Pizza();
|
Pizza pz3 = new Pizza();
|
||||||
pz3.setStatus(Pizza.PizzaStatus.ORDERED);
|
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||||
|
|
||||||
Pizza pz4 = new Pizza();
|
Pizza pz4 = new Pizza();
|
||||||
pz4.setStatus(Pizza.PizzaStatus.READY);
|
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||||
|
|
||||||
pzList.add(pz1);
|
pzList.add(pz1);
|
||||||
pzList.add(pz2);
|
pzList.add(pz2);
|
||||||
|
@ -48,33 +48,34 @@ public class PizzaTest {
|
||||||
|
|
||||||
List<Pizza> pzList = new ArrayList<>();
|
List<Pizza> pzList = new ArrayList<>();
|
||||||
Pizza pz1 = new Pizza();
|
Pizza pz1 = new Pizza();
|
||||||
pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
|
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
|
||||||
|
|
||||||
Pizza pz2 = new Pizza();
|
Pizza pz2 = new Pizza();
|
||||||
pz2.setStatus(Pizza.PizzaStatus.ORDERED);
|
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||||
|
|
||||||
Pizza pz3 = new Pizza();
|
Pizza pz3 = new Pizza();
|
||||||
pz3.setStatus(Pizza.PizzaStatus.ORDERED);
|
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||||
|
|
||||||
Pizza pz4 = new Pizza();
|
Pizza pz4 = new Pizza();
|
||||||
pz4.setStatus(Pizza.PizzaStatus.READY);
|
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||||
|
|
||||||
pzList.add(pz1);
|
pzList.add(pz1);
|
||||||
pzList.add(pz2);
|
pzList.add(pz2);
|
||||||
pzList.add(pz3);
|
pzList.add(pz3);
|
||||||
pzList.add(pz4);
|
pzList.add(pz4);
|
||||||
|
|
||||||
EnumMap<Pizza.PizzaStatus, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
|
EnumMap<Pizza.PizzaStatusEnum, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
|
||||||
assertTrue(map.get(Pizza.PizzaStatus.DELIVERED).size() == 1);
|
assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
|
||||||
assertTrue(map.get(Pizza.PizzaStatus.ORDERED).size() == 2);
|
assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
|
||||||
assertTrue(map.get(Pizza.PizzaStatus.READY).size() == 1);
|
assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
|
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
|
||||||
Pizza pz = new Pizza();
|
Pizza pz = new Pizza();
|
||||||
pz.setStatus(Pizza.PizzaStatus.READY);
|
pz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||||
pz.deliver();
|
pz.deliver();
|
||||||
assertTrue(pz.getStatus() == Pizza.PizzaStatus.DELIVERED);
|
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -13,7 +13,7 @@ import java.nio.file.Paths;
|
||||||
import org.apache.commons.io.FileUtils;
|
import org.apache.commons.io.FileUtils;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class JavaFileIntegrationTest {
|
public class JavaFileUnitTest {
|
||||||
|
|
||||||
// create a file
|
// create a file
|
||||||
|
|
|
@ -23,7 +23,7 @@ import java.util.Scanner;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class JavaReadFromFileTest {
|
public class JavaReadFromFileUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenReadWithBufferedReader_thenCorrect() throws IOException {
|
public void whenReadWithBufferedReader_thenCorrect() throws IOException {
|
||||||
|
@ -111,7 +111,7 @@ public class JavaReadFromFileTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
|
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
|
||||||
final String expected_value = "青空";
|
final String expected_value = "�空";
|
||||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
|
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
|
||||||
final String currentLine = reader.readLine();
|
final String currentLine = reader.readLine();
|
||||||
reader.close();
|
reader.close();
|
|
@ -15,7 +15,7 @@ import java.util.Scanner;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class JavaScannerTest {
|
public class JavaScannerUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenReadFileWithScanner_thenCorrect() throws IOException {
|
public void whenReadFileWithScanner_thenCorrect() throws IOException {
|
|
@ -26,7 +26,7 @@ import java.nio.file.Paths;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class JavaWriteToFileTest {
|
public class JavaWriteToFileUnitTest {
|
||||||
|
|
||||||
private String fileName = "src/test/resources/test_write.txt";
|
private String fileName = "src/test/resources/test_write.txt";
|
||||||
private String fileName1 = "src/test/resources/test_write_1.txt";
|
private String fileName1 = "src/test/resources/test_write_1.txt";
|
|
@ -7,7 +7,7 @@ import java.util.List;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class ListAssertJTest {
|
public class ListAssertJUnitTest {
|
||||||
|
|
||||||
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
|
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
|
||||||
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
|
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
|
||||||
|
@ -15,9 +15,7 @@ public class ListAssertJTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
|
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
|
||||||
assertThat(list1)
|
assertThat(list1).isEqualTo(list2).isNotEqualTo(list3);
|
||||||
.isEqualTo(list2)
|
|
||||||
.isNotEqualTo(list3);
|
|
||||||
|
|
||||||
assertThat(list1.equals(list2)).isTrue();
|
assertThat(list1.equals(list2)).isTrue();
|
||||||
assertThat(list1.equals(list3)).isFalse();
|
assertThat(list1.equals(list3)).isFalse();
|
|
@ -6,7 +6,7 @@ import org.testng.annotations.Test;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class ListTestNGTest {
|
public class ListTestNgUnitTest {
|
||||||
|
|
||||||
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
|
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
|
||||||
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
|
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
|
|
@ -1,9 +1,10 @@
|
||||||
package org.baeldung.java.md5;
|
package org.baeldung.java.md5;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.security.MessageDigest;
|
import java.security.MessageDigest;
|
||||||
import java.security.NoSuchAlgorithmException;
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
@ -11,20 +12,12 @@ import java.security.NoSuchAlgorithmException;
|
||||||
import javax.xml.bind.DatatypeConverter;
|
import javax.xml.bind.DatatypeConverter;
|
||||||
|
|
||||||
import org.apache.commons.codec.digest.DigestUtils;
|
import org.apache.commons.codec.digest.DigestUtils;
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.google.common.hash.HashCode;
|
import com.google.common.hash.HashCode;
|
||||||
import com.google.common.hash.Hashing;
|
import com.google.common.hash.Hashing;
|
||||||
|
|
||||||
import java.io.File;
|
public class JavaMD5UnitTest {
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.*;
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
|
|
||||||
|
|
||||||
public class JavaMD5Test {
|
|
||||||
|
|
||||||
|
|
||||||
String filename = "src/test/resources/test_md5.txt";
|
String filename = "src/test/resources/test_md5.txt";
|
||||||
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
|
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
|
||||||
|
@ -32,8 +25,6 @@ public class JavaMD5Test {
|
||||||
String hash = "35454B055CC325EA1AF2126E27707052";
|
String hash = "35454B055CC325EA1AF2126E27707052";
|
||||||
String password = "ILoveJava";
|
String password = "ILoveJava";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException {
|
public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException {
|
||||||
String hash = "35454B055CC325EA1AF2126E27707052";
|
String hash = "35454B055CC325EA1AF2126E27707052";
|
||||||
|
@ -55,8 +46,7 @@ public class JavaMD5Test {
|
||||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||||
md.update(Files.readAllBytes(Paths.get(filename)));
|
md.update(Files.readAllBytes(Paths.get(filename)));
|
||||||
byte[] digest = md.digest();
|
byte[] digest = md.digest();
|
||||||
String myChecksum = DatatypeConverter
|
String myChecksum = DatatypeConverter.printHexBinary(digest).toUpperCase();
|
||||||
.printHexBinary(digest).toUpperCase();
|
|
||||||
|
|
||||||
assertThat(myChecksum.equals(checksum)).isTrue();
|
assertThat(myChecksum.equals(checksum)).isTrue();
|
||||||
}
|
}
|
||||||
|
@ -66,25 +56,20 @@ public class JavaMD5Test {
|
||||||
String hash = "35454B055CC325EA1AF2126E27707052";
|
String hash = "35454B055CC325EA1AF2126E27707052";
|
||||||
String password = "ILoveJava";
|
String password = "ILoveJava";
|
||||||
|
|
||||||
String md5Hex = DigestUtils
|
String md5Hex = DigestUtils.md5Hex(password).toUpperCase();
|
||||||
.md5Hex(password).toUpperCase();
|
|
||||||
|
|
||||||
assertThat(md5Hex.equals(hash)).isTrue();
|
assertThat(md5Hex.equals(hash)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException {
|
public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException {
|
||||||
String filename = "src/test/resources/test_md5.txt";
|
String filename = "src/test/resources/test_md5.txt";
|
||||||
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
|
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
|
||||||
|
|
||||||
HashCode hash = com.google.common.io.Files
|
HashCode hash = com.google.common.io.Files.hash(new File(filename), Hashing.md5());
|
||||||
.hash(new File(filename), Hashing.md5());
|
String myChecksum = hash.toString().toUpperCase();
|
||||||
String myChecksum = hash.toString()
|
|
||||||
.toUpperCase();
|
|
||||||
|
|
||||||
assertThat(myChecksum.equals(checksum)).isTrue();
|
assertThat(myChecksum.equals(checksum)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
|
@ -6,7 +6,7 @@ import java.util.TimerTask;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class SandboxJavaTest {
|
public class SandboxJavaManualTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException {
|
public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException {
|
|
@ -11,6 +11,7 @@
|
||||||
<jee.version>7.0</jee.version>
|
<jee.version>7.0</jee.version>
|
||||||
<hibernate.version>5.1.0.Final</hibernate.version>
|
<hibernate.version>5.1.0.Final</hibernate.version>
|
||||||
<mysql.version>5.1.38</mysql.version>
|
<mysql.version>5.1.38</mysql.version>
|
||||||
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -33,6 +34,16 @@
|
||||||
</descriptorRefs>
|
</descriptorRefs>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>${maven-surefire-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
|
|
@ -15,7 +15,7 @@ import org.junit.Test;
|
||||||
|
|
||||||
import com.baeldung.jpa.model.Car;
|
import com.baeldung.jpa.model.Car;
|
||||||
|
|
||||||
public class StoredProcedureTest {
|
public class StoredProcedureIntegrationTest {
|
||||||
|
|
||||||
private static EntityManagerFactory factory = null;
|
private static EntityManagerFactory factory = null;
|
||||||
private static EntityManager entityManager = null;
|
private static EntityManager entityManager = null;
|
|
@ -0,0 +1,172 @@
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.DataOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import org.json.JSONArray;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import model.Student;
|
||||||
|
import play.test.*;
|
||||||
|
import static play.test.Helpers.*;
|
||||||
|
|
||||||
|
public class ApplicationTest{
|
||||||
|
private static final String BASE_URL = "http://localhost:9000";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testInServer() throws Exception {
|
||||||
|
TestServer server = testServer(3333);
|
||||||
|
running(server, () -> {
|
||||||
|
try {
|
||||||
|
WSClient ws = play.libs.ws.WS.newClient(3333);
|
||||||
|
CompletionStage<WSResponse> completionStage = ws.url("/").get();
|
||||||
|
WSResponse response = completionStage.toCompletableFuture().get();
|
||||||
|
ws.close();
|
||||||
|
assertEquals(OK, response.getStatus());
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void whenCreatesRecord_thenCorrect() {
|
||||||
|
Student student = new Student("jody", "west", 50);
|
||||||
|
JSONObject obj = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student)));
|
||||||
|
assertTrue(obj.getBoolean("isSuccessfull"));
|
||||||
|
JSONObject body = obj.getJSONObject("body");
|
||||||
|
assertEquals(student.getAge(), body.getInt("age"));
|
||||||
|
assertEquals(student.getFirstName(), body.getString("firstName"));
|
||||||
|
assertEquals(student.getLastName(), body.getString("lastName"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDeletesCreatedRecord_thenCorrect() {
|
||||||
|
Student student = new Student("Usain", "Bolt", 25);
|
||||||
|
JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body");
|
||||||
|
int id = ob1.getInt("id");
|
||||||
|
JSONObject obj1 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject()));
|
||||||
|
assertTrue(obj1.getBoolean("isSuccessfull"));
|
||||||
|
makeRequest(BASE_URL + "/" + id, "DELETE", null);
|
||||||
|
JSONObject obj2 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject()));
|
||||||
|
assertFalse(obj2.getBoolean("isSuccessfull"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUpdatesCreatedRecord_thenCorrect() {
|
||||||
|
Student student = new Student("john", "doe", 50);
|
||||||
|
JSONObject body1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body");
|
||||||
|
assertEquals(student.getAge(), body1.getInt("age"));
|
||||||
|
int newAge = 60;
|
||||||
|
body1.put("age", newAge);
|
||||||
|
JSONObject body2 = new JSONObject(makeRequest(BASE_URL, "PUT", body1)).getJSONObject("body");
|
||||||
|
assertFalse(student.getAge() == body2.getInt("age"));
|
||||||
|
assertTrue(newAge == body2.getInt("age"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetsAllRecords_thenCorrect() {
|
||||||
|
Student student1 = new Student("jane", "daisy", 50);
|
||||||
|
Student student2 = new Student("john", "daniel", 60);
|
||||||
|
Student student3 = new Student("don", "mason", 55);
|
||||||
|
Student student4 = new Student("scarlet", "ohara", 90);
|
||||||
|
|
||||||
|
makeRequest(BASE_URL, "POST", new JSONObject(student1));
|
||||||
|
makeRequest(BASE_URL, "POST", new JSONObject(student2));
|
||||||
|
makeRequest(BASE_URL, "POST", new JSONObject(student3));
|
||||||
|
makeRequest(BASE_URL, "POST", new JSONObject(student4));
|
||||||
|
|
||||||
|
JSONObject objects = new JSONObject(makeRequest(BASE_URL, "GET", null));
|
||||||
|
assertTrue(objects.getBoolean("isSuccessfull"));
|
||||||
|
JSONArray array = objects.getJSONArray("body");
|
||||||
|
assertTrue(array.length() >= 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String makeRequest(String myUrl, String httpMethod, JSONObject parameters) {
|
||||||
|
|
||||||
|
URL url = null;
|
||||||
|
try {
|
||||||
|
url = new URL(myUrl);
|
||||||
|
} catch (MalformedURLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
HttpURLConnection conn = null;
|
||||||
|
try {
|
||||||
|
|
||||||
|
conn = (HttpURLConnection) url.openConnection();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
conn.setDoInput(true);
|
||||||
|
|
||||||
|
conn.setReadTimeout(10000);
|
||||||
|
|
||||||
|
conn.setRequestProperty("Content-Type", "application/json");
|
||||||
|
DataOutputStream dos = null;
|
||||||
|
int respCode = 0;
|
||||||
|
String inputString = null;
|
||||||
|
try {
|
||||||
|
conn.setRequestMethod(httpMethod);
|
||||||
|
|
||||||
|
if (Arrays.asList("POST", "PUT").contains(httpMethod)) {
|
||||||
|
String params = parameters.toString();
|
||||||
|
|
||||||
|
conn.setDoOutput(true);
|
||||||
|
|
||||||
|
dos = new DataOutputStream(conn.getOutputStream());
|
||||||
|
dos.writeBytes(params);
|
||||||
|
dos.flush();
|
||||||
|
dos.close();
|
||||||
|
}
|
||||||
|
respCode = conn.getResponseCode();
|
||||||
|
if (respCode != 200 && respCode != 201) {
|
||||||
|
String error = inputStreamToString(conn.getErrorStream());
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
inputString = inputStreamToString(conn.getInputStream());
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return inputString;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String inputStreamToString(InputStream is) {
|
||||||
|
BufferedReader br = null;
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
|
||||||
|
String line;
|
||||||
|
try {
|
||||||
|
|
||||||
|
br = new BufferedReader(new InputStreamReader(is));
|
||||||
|
while ((line = br.readLine()) != null) {
|
||||||
|
sb.append(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} finally {
|
||||||
|
if (br != null) {
|
||||||
|
try {
|
||||||
|
br.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return sb.toString();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
2
pom.xml
2
pom.xml
|
@ -58,7 +58,7 @@
|
||||||
|
|
||||||
<module>mockito</module>
|
<module>mockito</module>
|
||||||
<module>mocks</module>
|
<module>mocks</module>
|
||||||
<module>mutation-testing</module>
|
<module>testing</module>
|
||||||
|
|
||||||
<module>orika</module>
|
<module>orika</module>
|
||||||
|
|
||||||
|
|
|
@ -10,6 +10,8 @@
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<resteasy.version>3.0.14.Final</resteasy.version>
|
<resteasy.version>3.0.14.Final</resteasy.version>
|
||||||
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
<cargo-maven2-plugin.version>1.6.0</cargo-maven2-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -23,6 +25,35 @@
|
||||||
<target>1.8</target>
|
<target>1.8</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>${maven-surefire-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.cargo</groupId>
|
||||||
|
<artifactId>cargo-maven2-plugin</artifactId>
|
||||||
|
<version>${cargo-maven2-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<wait>true</wait>
|
||||||
|
<container>
|
||||||
|
<containerId>jetty8x</containerId>
|
||||||
|
<type>embedded</type>
|
||||||
|
</container>
|
||||||
|
<configuration>
|
||||||
|
<properties>
|
||||||
|
<cargo.servlet.port>8082</cargo.servlet.port>
|
||||||
|
</properties>
|
||||||
|
</configuration>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
@ -73,5 +104,66 @@
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<profile>
|
||||||
|
<id>live</id>
|
||||||
|
<build>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>integration-test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>test</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
<includes>
|
||||||
|
<include>**/*LiveTest.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<systemPropertyVariables>
|
||||||
|
<test.mime>json</test.mime>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.cargo</groupId>
|
||||||
|
<artifactId>cargo-maven2-plugin</artifactId>
|
||||||
|
<version>${cargo-maven2-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<wait>false</wait>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>start-server</id>
|
||||||
|
<phase>pre-integration-test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>start</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>stop-server</id>
|
||||||
|
<phase>post-integration-test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>stop</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -1,7 +1,15 @@
|
||||||
package com.baeldung.server;
|
package com.baeldung.server;
|
||||||
|
|
||||||
import com.baeldung.client.ServicesInterface;
|
import java.io.InputStream;
|
||||||
import com.baeldung.model.Movie;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import javax.naming.NamingException;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import javax.ws.rs.core.UriBuilder;
|
||||||
|
|
||||||
import org.apache.commons.io.IOUtils;
|
import org.apache.commons.io.IOUtils;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.client.HttpClients;
|
||||||
|
@ -14,18 +22,13 @@ import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
|
||||||
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
|
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import javax.naming.NamingException;
|
|
||||||
import javax.ws.rs.core.Response;
|
|
||||||
import javax.ws.rs.core.UriBuilder;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
|
|
||||||
public class RestEasyClientTest {
|
import com.baeldung.client.ServicesInterface;
|
||||||
|
import com.baeldung.model.Movie;
|
||||||
|
|
||||||
public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest");
|
public class RestEasyClientLiveTest {
|
||||||
|
|
||||||
|
public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8082/RestEasyTutorial/rest");
|
||||||
Movie transformerMovie = null;
|
Movie transformerMovie = null;
|
||||||
Movie batmanMovie = null;
|
Movie batmanMovie = null;
|
||||||
ObjectMapper jsonMapper = null;
|
ObjectMapper jsonMapper = null;
|
||||||
|
@ -35,22 +38,22 @@ public class RestEasyClientTest {
|
||||||
|
|
||||||
jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||||
jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
|
jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
|
||||||
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
|
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
|
||||||
jsonMapper.setDateFormat(sdf);
|
jsonMapper.setDateFormat(sdf);
|
||||||
|
|
||||||
try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) {
|
try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/transformer.json")) {
|
||||||
String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
|
final String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
|
||||||
transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class);
|
transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class);
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
throw new RuntimeException("Test is going to die ...", e);
|
throw new RuntimeException("Test is going to die ...", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) {
|
try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/batman.json")) {
|
||||||
String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
|
final String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
|
||||||
batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class);
|
batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class);
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
throw new RuntimeException("Test is going to die ...", e);
|
throw new RuntimeException("Test is going to die ...", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -58,41 +61,41 @@ public class RestEasyClientTest {
|
||||||
@Test
|
@Test
|
||||||
public void testListAllMovies() {
|
public void testListAllMovies() {
|
||||||
|
|
||||||
ResteasyClient client = new ResteasyClientBuilder().build();
|
final ResteasyClient client = new ResteasyClientBuilder().build();
|
||||||
ResteasyWebTarget target = client.target(FULL_PATH);
|
final ResteasyWebTarget target = client.target(FULL_PATH);
|
||||||
ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
||||||
|
|
||||||
Response moviesResponse = proxy.addMovie(transformerMovie);
|
Response moviesResponse = proxy.addMovie(transformerMovie);
|
||||||
moviesResponse.close();
|
moviesResponse.close();
|
||||||
moviesResponse = proxy.addMovie(batmanMovie);
|
moviesResponse = proxy.addMovie(batmanMovie);
|
||||||
moviesResponse.close();
|
moviesResponse.close();
|
||||||
|
|
||||||
List<Movie> movies = proxy.listMovies();
|
final List<Movie> movies = proxy.listMovies();
|
||||||
System.out.println(movies);
|
System.out.println(movies);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testMovieByImdbId() {
|
public void testMovieByImdbId() {
|
||||||
|
|
||||||
String transformerImdbId = "tt0418279";
|
final String transformerImdbId = "tt0418279";
|
||||||
|
|
||||||
ResteasyClient client = new ResteasyClientBuilder().build();
|
final ResteasyClient client = new ResteasyClientBuilder().build();
|
||||||
ResteasyWebTarget target = client.target(FULL_PATH);
|
final ResteasyWebTarget target = client.target(FULL_PATH);
|
||||||
ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
||||||
|
|
||||||
Response moviesResponse = proxy.addMovie(transformerMovie);
|
final Response moviesResponse = proxy.addMovie(transformerMovie);
|
||||||
moviesResponse.close();
|
moviesResponse.close();
|
||||||
|
|
||||||
Movie movies = proxy.movieByImdbId(transformerImdbId);
|
final Movie movies = proxy.movieByImdbId(transformerImdbId);
|
||||||
System.out.println(movies);
|
System.out.println(movies);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddMovie() {
|
public void testAddMovie() {
|
||||||
|
|
||||||
ResteasyClient client = new ResteasyClientBuilder().build();
|
final ResteasyClient client = new ResteasyClientBuilder().build();
|
||||||
ResteasyWebTarget target = client.target(FULL_PATH);
|
final ResteasyWebTarget target = client.target(FULL_PATH);
|
||||||
ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
||||||
|
|
||||||
Response moviesResponse = proxy.addMovie(batmanMovie);
|
Response moviesResponse = proxy.addMovie(batmanMovie);
|
||||||
moviesResponse.close();
|
moviesResponse.close();
|
||||||
|
@ -109,17 +112,15 @@ public class RestEasyClientTest {
|
||||||
@Test
|
@Test
|
||||||
public void testAddMovieMultiConnection() {
|
public void testAddMovieMultiConnection() {
|
||||||
|
|
||||||
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
|
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
|
||||||
CloseableHttpClient httpClient = HttpClients.custom()
|
final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
|
||||||
.setConnectionManager(cm)
|
final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
|
||||||
.build();
|
final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
|
||||||
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
|
final ResteasyWebTarget target = client.target(FULL_PATH);
|
||||||
ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
|
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
||||||
ResteasyWebTarget target = client.target(FULL_PATH);
|
|
||||||
ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
|
||||||
|
|
||||||
Response batmanResponse = proxy.addMovie(batmanMovie);
|
final Response batmanResponse = proxy.addMovie(batmanMovie);
|
||||||
Response transformerResponse = proxy.addMovie(transformerMovie);
|
final Response transformerResponse = proxy.addMovie(transformerMovie);
|
||||||
|
|
||||||
if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
|
if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
|
||||||
System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
|
System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
|
||||||
|
@ -132,16 +133,14 @@ public class RestEasyClientTest {
|
||||||
transformerResponse.close();
|
transformerResponse.close();
|
||||||
cm.close();
|
cm.close();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDeleteMovie() {
|
public void testDeleteMovie() {
|
||||||
|
|
||||||
ResteasyClient client = new ResteasyClientBuilder().build();
|
final ResteasyClient client = new ResteasyClientBuilder().build();
|
||||||
ResteasyWebTarget target = client.target(FULL_PATH);
|
final ResteasyWebTarget target = client.target(FULL_PATH);
|
||||||
ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
||||||
|
|
||||||
Response moviesResponse = proxy.addMovie(batmanMovie);
|
Response moviesResponse = proxy.addMovie(batmanMovie);
|
||||||
moviesResponse.close();
|
moviesResponse.close();
|
||||||
|
@ -159,9 +158,9 @@ public class RestEasyClientTest {
|
||||||
@Test
|
@Test
|
||||||
public void testUpdateMovie() {
|
public void testUpdateMovie() {
|
||||||
|
|
||||||
ResteasyClient client = new ResteasyClientBuilder().build();
|
final ResteasyClient client = new ResteasyClientBuilder().build();
|
||||||
ResteasyWebTarget target = client.target(FULL_PATH);
|
final ResteasyWebTarget target = client.target(FULL_PATH);
|
||||||
ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
|
||||||
|
|
||||||
Response moviesResponse = proxy.addMovie(batmanMovie);
|
Response moviesResponse = proxy.addMovie(batmanMovie);
|
||||||
moviesResponse.close();
|
moviesResponse.close();
|
|
@ -1,9 +1,9 @@
|
||||||
package org.baeldung.persistence;
|
package org.baeldung.persistence;
|
||||||
|
|
||||||
import org.baeldung.persistence.query.JPACriteriaQueryTest;
|
import org.baeldung.persistence.query.JPACriteriaQueryIntegrationTest;
|
||||||
import org.baeldung.persistence.query.JPAQuerydslTest;
|
import org.baeldung.persistence.query.JPAQuerydslIntegrationTest;
|
||||||
import org.baeldung.persistence.query.JPASpecificationTest;
|
import org.baeldung.persistence.query.JPASpecificationIntegrationTest;
|
||||||
import org.baeldung.persistence.query.RsqlTest;
|
import org.baeldung.persistence.query.RsqlIntegrationTest;
|
||||||
import org.baeldung.persistence.service.FooServicePersistenceIntegrationTest;
|
import org.baeldung.persistence.service.FooServicePersistenceIntegrationTest;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.junit.runners.Suite;
|
import org.junit.runners.Suite;
|
||||||
|
@ -11,11 +11,11 @@ import org.junit.runners.Suite;
|
||||||
@RunWith(Suite.class)
|
@RunWith(Suite.class)
|
||||||
@Suite.SuiteClasses({
|
@Suite.SuiteClasses({
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
RsqlTest.class
|
RsqlIntegrationTest.class
|
||||||
,JPASpecificationTest.class
|
,JPASpecificationIntegrationTest.class
|
||||||
,FooServicePersistenceIntegrationTest.class
|
,FooServicePersistenceIntegrationTest.class
|
||||||
,JPAQuerydslTest.class
|
,JPAQuerydslIntegrationTest.class
|
||||||
,JPACriteriaQueryTest.class
|
,JPACriteriaQueryIntegrationTest.class
|
||||||
}) //
|
}) //
|
||||||
public class PersistenceTestSuite {
|
public class PersistenceTestSuite {
|
||||||
|
|
||||||
|
|
|
@ -24,7 +24,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||||
@ContextConfiguration(classes = { PersistenceConfig.class })
|
@ContextConfiguration(classes = { PersistenceConfig.class })
|
||||||
@Transactional
|
@Transactional
|
||||||
@Rollback
|
@Rollback
|
||||||
public class JPACriteriaQueryTest {
|
public class JPACriteriaQueryIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IUserDAO userApi;
|
private IUserDAO userApi;
|
|
@ -23,7 +23,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||||
@ContextConfiguration(classes = { PersistenceConfig.class })
|
@ContextConfiguration(classes = { PersistenceConfig.class })
|
||||||
@Transactional
|
@Transactional
|
||||||
@Rollback
|
@Rollback
|
||||||
public class JPAQuerydslTest {
|
public class JPAQuerydslIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private MyUserRepository repo;
|
private MyUserRepository repo;
|
|
@ -26,7 +26,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||||
@ContextConfiguration(classes = { PersistenceConfig.class })
|
@ContextConfiguration(classes = { PersistenceConfig.class })
|
||||||
@Transactional
|
@Transactional
|
||||||
@Rollback
|
@Rollback
|
||||||
public class JPASpecificationTest {
|
public class JPASpecificationIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private UserRepository repository;
|
private UserRepository repository;
|
|
@ -27,7 +27,7 @@ import cz.jirutka.rsql.parser.ast.Node;
|
||||||
@ContextConfiguration(classes = { PersistenceConfig.class })
|
@ContextConfiguration(classes = { PersistenceConfig.class })
|
||||||
@Transactional
|
@Transactional
|
||||||
@Rollback
|
@Rollback
|
||||||
public class RsqlTest {
|
public class RsqlIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private UserRepository repository;
|
private UserRepository repository;
|
|
@ -23,7 +23,7 @@ import org.springframework.web.context.WebApplicationContext;
|
||||||
@WebAppConfiguration
|
@WebAppConfiguration
|
||||||
@Transactional
|
@Transactional
|
||||||
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
||||||
public class LoggerInterceptorTest {
|
public class LoggerInterceptorIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
WebApplicationContext wac;
|
WebApplicationContext wac;
|
|
@ -28,7 +28,7 @@ import org.springframework.web.context.WebApplicationContext;
|
||||||
@Transactional
|
@Transactional
|
||||||
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
||||||
@WithMockUser(username = "admin", roles = { "USER", "ADMIN" })
|
@WithMockUser(username = "admin", roles = { "USER", "ADMIN" })
|
||||||
public class SessionTimerInterceptorTest {
|
public class SessionTimerInterceptorIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
WebApplicationContext wac;
|
WebApplicationContext wac;
|
|
@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||||
@Transactional
|
@Transactional
|
||||||
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
||||||
@WithMockUser(username = "admin", roles = { "USER", "ADMIN" })
|
@WithMockUser(username = "admin", roles = { "USER", "ADMIN" })
|
||||||
public class UserInterceptorTest {
|
public class UserInterceptorIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
WebApplicationContext wac;
|
WebApplicationContext wac;
|
Loading…
Reference in New Issue