Skip to content

Instantly share code, notes, and snippets.

@faveoled
Created February 16, 2023 10:24
Show Gist options
  • Save faveoled/5437b7a63d0cf4d13d3bfd74ae7960d2 to your computer and use it in GitHub Desktop.
Save faveoled/5437b7a63d0cf4d13d3bfd74ae7960d2 to your computer and use it in GitHub Desktop.
J2CL Java single-file unit testing
import elemental2.dom.DomGlobal;
import elemental2.promise.Promise;
import java.util.List;
import java.util.function.Supplier;
public class Tests {
public static final String GREEN_CIRCLE = "\uD83D\uDFE2";
public static final String RED_CIRCLE = "\uD83D\uDD34";
public void runTests() {
runTest("test1", this::test1);
runTest("test2", this::test2);
runTest("test3", this::test3);
}
public void test1() {
String expected = "1";
String actual = Integer.toString(1);
assertEquals(expected, actual);
}
public void test2() {
String expected = "2";
String actual = Integer.toString(1);
assertEquals(expected, actual);
}
private Promise<?> test3() {
Promise<List<RatingItem>> promise = new ApiClient().fetchRatings();
return promise.then(
success -> {
assertEquals(7412, success.size());
return null;
}
);
}
private void runTest(String testName, Runnable testMethod) {
String errorMsg;
try {
testMethod.run();
errorMsg = null;
} catch (Exception e) {
errorMsg = e.toString();
}
DomGlobal.console.log("Test %s: %s", testName, errorMsg == null ? GREEN_CIRCLE : RED_CIRCLE + ". " + errorMsg);
}
private void runTest(String testName, Supplier<Promise<?>> testMethod) {
try {
Promise<?> promise = testMethod.get();
promise.then(
success -> {
DomGlobal.console.log("Test %s: %s", testName, GREEN_CIRCLE);
return null;
},
failure -> {
DomGlobal.console.log("Test %s: %s", testName, RED_CIRCLE + ". " + failure.toString());
return null;
}
);
} catch (Exception e) {
DomGlobal.console.log("Test %s: %s", testName, RED_CIRCLE + ". " + e);
}
}
private void assertEquals(Object expected, Object actual) {
if (!expected.equals(actual)) {
throw new RuntimeException("Failed: expected " + expected + ", got " + actual);
}
}
}
// new Tests().runTests();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment