Skip to content

Instantly share code, notes, and snippets.

@jmini
Created March 8, 2022 06:53
Show Gist options
  • Save jmini/b97fefb289d6efa670d3cc5c010af89c to your computer and use it in GitHub Desktop.
Save jmini/b97fefb289d6efa670d3cc5c010af89c to your computer and use it in GitHub Desktop.
Write and execute Junit 5 unit tests directly in Jbang
///usr/bin/env jbang "$0" "$@" ; exit $?
// Junit console to start the test engine:
//DEPS org.junit.platform:junit-platform-console:1.8.2
// engine to run the tests (tests are written with Junit5):
//DEPS org.junit.jupiter:junit-jupiter-engine:5.8.2
import static org.junit.jupiter.api.Assertions.fail;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import org.junit.platform.console.options.CommandLineOptions;
import org.junit.platform.console.tasks.ConsoleTestExecutor;
public class runTests {
@Test
void testName() throws Exception {
fail("This is an example test");
}
public static void main(String... args) throws Exception {
if (args == null || args.length != 1) {
System.err.println("Output directory is not specified. Usage:");
System.err.println(runTests.class.getSimpleName() + ".java <reports output directory>");
System.exit(1);
throw new IllegalStateException("Unreachable code");
}
CommandLineOptions options = new CommandLineOptions();
options.setSelectedClasses(Collections.singletonList(runTests.class.getName()));
options.setReportsDir(Paths.get(args[0]));
new ConsoleTestExecutor(options).execute(new PrintWriter(System.out));
}
}
@jmini
Copy link
Author

jmini commented Mar 8, 2022

This is a jbang script that:

  • defines some JUnit 5 tests. Example: testName() annotated with @Test
  • can be executed to run the define test and to publish the test result in the folder passed as parameter.

Usage:

./runTests.java /path/to/output/dir

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment