Polish SerializationTestUtils, clean up warnings, etc.

This commit is contained in:
Sam Brannen
2020-06-20 18:17:03 +02:00
parent 9d5881e0ad
commit ab0e651547
43 changed files with 133 additions and 126 deletions

View File

@@ -75,10 +75,10 @@ class SocketUtilsTests {
}
@Test
@SuppressWarnings("try")
void findAvailableTcpPortWhenPortOnLoopbackInterfaceIsNotAvailable() throws Exception {
int port = SocketUtils.findAvailableTcpPort();
try (ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(port, 1, InetAddress.getByName("localhost"))) {
assertThat(socket).isNotNull();
// will only look for the exact port
assertThatIllegalStateException().isThrownBy(() ->
SocketUtils.findAvailableTcpPort(port, port))
@@ -149,10 +149,10 @@ class SocketUtilsTests {
}
@Test
@SuppressWarnings("try")
void findAvailableUdpPortWhenPortOnLoopbackInterfaceIsNotAvailable() throws Exception {
int port = SocketUtils.findAvailableUdpPort();
try (DatagramSocket socket = new DatagramSocket(port, InetAddress.getByName("localhost"))) {
assertThat(socket).isNotNull();
// will only look for the exact port
assertThatIllegalStateException().isThrownBy(() ->
SocketUtils.findAvailableUdpPort(port, port))

View File

@@ -26,9 +26,11 @@ import java.io.OutputStream;
/**
* Utilities for testing serializability of objects.
* Exposes static methods for use in other test cases.
*
* <p>Exposes static methods for use in other test cases.
*
* @author Rod Johnson
* @author Sam Brannen
*/
public class SerializationTestUtils {
@@ -49,7 +51,8 @@ public class SerializationTestUtils {
}
}
public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException {
@SuppressWarnings("unchecked")
public static <T> T serializeAndDeserialize(T o) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(o);
@@ -59,7 +62,21 @@ public class SerializationTestUtils {
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
try (ObjectInputStream ois = new ObjectInputStream(is)) {
return ois.readObject();
return (T) ois.readObject();
}
}
public static <T> T serializeAndDeserialize(Object o, Class<T> expectedType) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(o);
oos.flush();
}
byte[] bytes = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
try (ObjectInputStream ois = new ObjectInputStream(is)) {
return expectedType.cast(ois.readObject());
}
}