Skip to content

Commit dadbe57

Browse files
authored
Refactoring Java tests: 1-17
- Refactor Java 6 tests: improve dynamic compilation and add assertions for class accessibility - Adjust wait time in Java 5 concurrency test - Correct file path in Java 17 deserialization test - Remove redundant whitespace in Java 4 file read test - Refactor functional interface declaration in Java 8 tests
1 parent 479e2d8 commit dadbe57

File tree

8 files changed

+45
-28
lines changed

8 files changed

+45
-28
lines changed

JavaReleases/src/test/java/pl/mperor/lab/java/Java1.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ public void testJavaBean() throws IOException, ClassNotFoundException {
5555
}
5656

5757
private void assertJavaBeanSerializationAndDeserialization(JavaBean bean) throws IOException, ClassNotFoundException {
58-
var file = new File("src/test/resources/bean");
58+
var file = new File("src/test/resources/bean.bin");
5959
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) {
6060
out.writeObject(bean);
6161
}
@@ -107,13 +107,13 @@ public void testRemoteMethodInvocationAkaRMI() throws RemoteException, NotBoundE
107107
HelloService stub = (HelloService) registry.lookup("HelloService");
108108

109109
// Call the remote method and verify the result
110-
Assertions.assertEquals("Hello World!", stub.sayHello());
110+
Assertions.assertEquals("Hello World!", stub.getMessage());
111111

112112
executor.shutdown();
113113
}
114114

115115
interface HelloService extends Remote {
116-
String sayHello() throws RemoteException;
116+
String getMessage() throws RemoteException;
117117
}
118118

119119
static class HelloServiceImpl extends UnicastRemoteObject implements HelloService {
@@ -122,7 +122,7 @@ protected HelloServiceImpl() throws RemoteException {
122122
}
123123

124124
@Override
125-
public String sayHello() throws RemoteException {
125+
public String getMessage() throws RemoteException {
126126
return "Hello World!";
127127
}
128128
}

JavaReleases/src/test/java/pl/mperor/lab/java/Java17.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ public void testRmiActivationRemoved() {
146146

147147
@Test
148148
public void testDeserializationFilters() throws IOException, ClassNotFoundException {
149-
var file = new File("src/test/resources/bean");
149+
var file = new File("src/test/resources/bean.bin");
150150

151151
var basePackageFilter = ObjectInputFilter.Config.createFilter("java.base/*;!*");
152152
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {

JavaReleases/src/test/java/pl/mperor/lab/java/Java3.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,14 @@ public void testJavaNamingAndDirectoryInterfaceAkaJNDILookup() throws NamingExce
2727
String bindingName = "hello";
2828
String bindingResult = "Hello World!";
2929

30-
Context context = new InitialContext();
31-
context.bind(bindingName, bindingResult);
32-
String lookupResult = (String) context.lookup(bindingName);
30+
Context ctx = new InitialContext();
31+
ctx.bind(bindingName, bindingResult);
32+
String lookupResult = (String) ctx.lookup(bindingName);
3333
Assertions.assertEquals(bindingResult, lookupResult);
3434

35-
context.unbind(bindingName);
35+
ctx.unbind(bindingName);
3636
Assertions.assertThrows(NamingException.class, () -> {
37-
context.lookup(bindingName);
37+
ctx.lookup(bindingName);
3838
});
3939
}
4040

JavaReleases/src/test/java/pl/mperor/lab/java/Java4.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import java.nio.channels.SocketChannel;
1313
import java.nio.file.Files;
1414
import java.nio.file.Path;
15-
import java.nio.file.Paths;
1615
import java.util.concurrent.CountDownLatch;
1716
import java.util.concurrent.Executors;
1817
import java.util.logging.Logger;
@@ -35,21 +34,22 @@ public void testAssertionKeyWord() {
3534

3635
@Test
3736
public void testNewInputOutputAkaNIO() throws IOException {
38-
Path path = Paths.get("src", "test", "resources", "nio.txt");
37+
Path path = Path.of("src", "test", "resources", "nio.txt");
3938
byte[] fileBytes = Files.readAllBytes(path);
4039
String content = new String(fileBytes);
40+
4141
Assertions.assertEquals("Hello NIO!", content);
4242
}
4343

4444
@Test
4545
public void testRegex() {
4646
Pattern pattern = Pattern.compile("<title>(.*)</title>", Pattern.DOTALL);
47-
Matcher matcher = pattern.matcher(getTestHtml());
47+
Matcher matcher = pattern.matcher(createTestHtml());
4848
Assertions.assertTrue(matcher.find());
4949
Assertions.assertEquals("Title", matcher.group(1));
5050
}
5151

52-
private String getTestHtml() {
52+
private String createTestHtml() {
5353
return """
5454
<!DOCTYPE html>
5555
<html lang="en">
@@ -89,6 +89,7 @@ public void testImageIO() throws IOException {
8989
BufferedImage image = ImageIO.read(new File("src/test/resources/imageio.png"));
9090
Assertions.assertTrue(ImageIO.write(image, "jpg", File.createTempFile("imageio", ".jpg")));
9191
}
92+
9293
@Test
9394
public void testServerClientSocketChannel() throws IOException, InterruptedException {
9495
int port = 8004;
@@ -124,5 +125,4 @@ private void handleConnectedClient(ServerSocket serverSocket) throws IOException
124125
}
125126
}
126127

127-
128128
}

JavaReleases/src/test/java/pl/mperor/lab/java/Java5.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public void testGenerics() {
3131
Box rawBox = new Box();
3232
rawBox.setContent("Hello").setContent(1);
3333
Assertions.assertThrows(ClassCastException.class, () -> {
34-
String rawBoxContent = (String) rawBox.getContent();
34+
String wrongTypeContent = (String) rawBox.getContent();
3535
});
3636
Integer rawBoxContent = (Integer) rawBox.getContent();
3737
Assertions.assertEquals(1, rawBoxContent);
@@ -124,7 +124,7 @@ public void testScheduledExecutor() throws InterruptedException {
124124
latch.countDown();
125125
}, 0, 100, TimeUnit.MILLISECONDS);
126126

127-
boolean completed = latch.await(300, TimeUnit.MILLISECONDS);
127+
boolean completed = latch.await(200, TimeUnit.MILLISECONDS);
128128
Assertions.assertTrue(completed, "Task did not execute twice in time");
129129
Assertions.assertEquals(2, counter.get());
130130

JavaReleases/src/test/java/pl/mperor/lab/java/Java6.java

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import org.junit.jupiter.api.Assertions;
44
import org.junit.jupiter.api.Test;
5+
import pl.mperor.lab.common.TestUtils;
56

67
import javax.script.ScriptEngine;
78
import javax.script.ScriptEngineManager;
@@ -11,6 +12,10 @@
1112
import java.awt.*;
1213
import java.io.File;
1314
import java.io.IOException;
15+
import java.lang.reflect.InvocationTargetException;
16+
import java.net.MalformedURLException;
17+
import java.net.URL;
18+
import java.net.URLClassLoader;
1419
import java.nio.file.Files;
1520

1621
/**
@@ -32,24 +37,36 @@ public void testScriptingLanguageSupport() throws ScriptException {
3237
}
3338

3439
@Test
35-
public void testJavaDynamicCompilation() throws IOException {
36-
File sourceFile = new File("./HelloWorld.java");
40+
public void testJavaDynamicCompilation() throws IOException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
41+
File sourceFile = new File("HelloWorld.java");
3742
String javaSourceCode = """
3843
public class HelloWorld {
39-
public static void main(String[] args) {
40-
System.out.println("Hello World!");
44+
public void sayHello() {
45+
System.out.print("Hello World!");
4146
}
4247
}
4348
""";
4449
Files.write(sourceFile.toPath(), javaSourceCode.getBytes());
4550

4651
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
4752
Assertions.assertNotNull(compiler, "JavaCompiler should not be null");
48-
4953
int compilationResult = compiler.run(null, null, null, sourceFile.getAbsolutePath());
5054
Assertions.assertEquals(0, compilationResult, "Compilation should succeed with result 0!");
55+
assertHelloWorldClassAccessible();
56+
5157
Assertions.assertTrue(sourceFile.delete(), "Source file should be deleted after compilation");
52-
Assertions.assertTrue(new File("./HelloWorld.class").delete(), "Now compilation result can be deleted!");
58+
Assertions.assertTrue(new File("HelloWorld.class").delete(), "Now compilation result can be deleted!");
59+
}
60+
61+
private void assertHelloWorldClassAccessible() throws MalformedURLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
62+
URL[] urls = {new File("").toURI().toURL()};
63+
URLClassLoader loader = new URLClassLoader(urls);
64+
Class<?> clazz = loader.loadClass("HelloWorld");
65+
Object instance = clazz.getDeclaredConstructor().newInstance();
66+
var readableOut = TestUtils.setTempSystemOut();
67+
clazz.getDeclaredMethod("sayHello").invoke(instance);
68+
Assertions.assertEquals(readableOut.all(), "Hello World!");
69+
TestUtils.resetSystemOut();
5370
}
5471

5572
@Test

JavaReleases/src/test/java/pl/mperor/lab/java/Java8.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,11 @@ public void testCustomFunctionalInterface() {
7272
assertFunctionalInterface(Testable.class);
7373
}
7474

75+
@FunctionalInterface
76+
public interface Testable {
77+
void test();
78+
}
79+
7580
private static void assertFunctionalInterface(Class<?> clazz) {
7681
if (!clazz.isInterface()) {
7782
Assertions.fail("Clazz is not an interface!");
@@ -86,11 +91,6 @@ private static void assertFunctionalInterface(Class<?> clazz) {
8691
"Functional interface should contain exactly one abstract method, but @FunctionalInterface is optional!");
8792
}
8893

89-
@FunctionalInterface
90-
public interface Testable {
91-
void test();
92-
}
93-
9494
@Test
9595
public void testDefaultAndStaticMethodsInInterface() throws NoSuchMethodException {
9696
Tester tester = () -> new Testable[]{

0 commit comments

Comments
 (0)