Skip to content

Instantly share code, notes, and snippets.

@larsbutler
Last active November 27, 2015 23:03
Show Gist options
  • Save larsbutler/bf2efa280abd1bddf239 to your computer and use it in GitHub Desktop.
Save larsbutler/bf2efa280abd1bddf239 to your computer and use it in GitHub Desktop.
Testable: super-lightweight unit testing lib for Java
To run the example tests, simply do:
$ javac ExampleTest.java
$ java ExampleTest
Here's what the output should look like:
tearDown()
testTwo: pass
Error in method: testOne
Testable$TestItFailure: 5 != 6
at Testable.assertEqual(Testable.java:53)
at ExampleTest.testOne(ExampleTest.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at Testable.doRunTests(Testable.java:119)
at Testable.runTests(Testable.java:79)
at ExampleTest.main(ExampleTest.java:60)
tearDown()
testOne: fail
1/2 tests ran successfully (failed: 1)
Note also that when one or more tests fail, the exit code of the test suite
will be 1 (error).
/**
Copyright (c) 2015, Lars Butler
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
public class ExampleTest extends Testable {
private int x;
private int y;
/**
* Run this before each test. This is optional.
*/
@Override
public void setUp() {
this.x = 5;
this.y = 6;
}
/**
* Run this after each test. This is optional.
*/
@Override
public void tearDown() {
// TODO: do something
System.err.println("tearDown()");
}
@Test
public void testOne() {
// Use `assertEqual` to test for basic equality.
// You can compare any object in this way.
assertEqual(this.x, this.y);
}
@Test
public void testTwo() {
// For more complex boolean comparisons, use `assertThat`.
assertThat(this.x < this.y);
}
public static void main(String [] args) {
new ExampleTest().runTests(true);
}
}
/**
Copyright (c) 2015, Lars Butler
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Testable {
/**
* Simple test annotation, to indicate that a method is a test method.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {}
@SuppressWarnings("serial")
public class TestItFailure extends RuntimeException {
public TestItFailure() {}
public TestItFailure(String message) {
super(message);
}
}
public void assertThat(boolean expr) throws TestItFailure {
if (!expr) {
throw new TestItFailure();
}
}
public void assertEqual(Object a, Object b) throws TestItFailure {
if (!a.equals(b)) {
throw new TestItFailure(String.format(
"%s != %s",
a.toString(),
b.toString()));
}
}
public void fail() {
assertThat(false);
}
/**
* Default `runTests` method; `verbose` defaults to false.
* See below.
*/
public void runTests() {
runTests(false);
}
/**
*
* @param verbose: if true, print stack traces of errors to stderr;
* otherwise, just show "pass" or "fail" for each test.
*/
public void runTests(boolean verbose) {
try {
int failures = doRunTests(verbose);
if (failures > 0) {
// If there are any failures, we should return
// with a proper exit code indicating the failure.
System.exit(1);
}
}
catch (Exception e) {
// Something unexpected happened.
e.printStackTrace();
System.exit(1);
}
}
/**
* Override in subclasses to specify custom setup commands for each test
* method.
*/
public void setUp() {}
/**
* Override in subclasses to specify custom teardown commands for each test
* method.
*/
public void tearDown() {}
private int doRunTests(boolean verbose) throws IllegalAccessException, IllegalArgumentException {
int testCount = 0;
int passCount = 0;
int failCount = 0;
for (Method meth: this.getClass().getDeclaredMethods()) {
// Check for `Test` annotations, in order to find test methods.
Annotation[] annots = meth.getAnnotationsByType(Testable.Test.class);
if (annots.length > 0) {
testCount++;
boolean pass = true;
try {
this.setUp();
meth.invoke(this);
}
catch (InvocationTargetException ex) {
if (verbose) {
System.err.println("Error in method: " + meth.getName());
ex.getTargetException().printStackTrace();
}
pass = false;
}
finally {
// Always teardown, no matter what
this.tearDown();
}
if (pass) {
passCount++;
}
else {
failCount++;
}
System.out.printf("%s: %s\n", meth.getName(), pass ? "pass": "fail");
}
}
System.out.printf(
"%d/%d tests ran successfully (failed: %d)\n",
passCount,
testCount,
failCount);
return failCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment