Skip to content

Instantly share code, notes, and snippets.

@hansenc
Created July 9, 2015 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hansenc/1d929fef7a7d95d14157 to your computer and use it in GitHub Desktop.
Save hansenc/1d929fef7a7d95d14157 to your computer and use it in GitHub Desktop.
LambdataRule PoC
package org.lambdatarunner;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
public class LambdataRule implements TestRule {
private TestSpecs specs;
public void specs(NullaryIntegerFunction testRunner, Datum... data) {
specs = new TestSpecs(Arrays.stream(data).map(datum -> new TestSpecImpl(testRunner, datum)).collect(toList()));
}
@Override
public Statement apply(Statement base, Description description) {
try {
base.evaluate(); //initializes specs
}
catch (Throwable throwable) {
throw new RuntimeException("Could not initialize specs", throwable);
}
if (specs == null) { //class contains no specs, skip
return new Statement() {
@Override
public void evaluate() throws Throwable {
//intentional no-op
}
};
}
else {
return new Statement() {
private List<Throwable> failures = new ArrayList<>();
@Override
public void evaluate() throws Throwable {
specs.getSpecs().forEach(this::checkSucceeds);
MultipleFailureException.assertEmpty(failures);
}
private void checkSucceeds(TestSpec testSpec) {
try {
testSpec.run();
}
catch (Throwable throwable) {
//gather test failures for reporting
failures.add(throwable);
}
}
};
}
}
}
package org.lambdatarunner;
import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;
public class LambdataRuleTest {
@Rule
public LambdataRule lambdata = new LambdataRule();
@Test
public void creatingSingleParamTest() {
lambdata.specs(i -> assertEquals((int) i, i * 1),
datum(1),
datum(2),
datum(3));
}
@Test
public void failingTest() {
lambdata.specs(i -> assertEquals((int) i, i * 2),
datum(1),
datum(2),
datum(3));
}
public static Datum datum(int i) {
return () -> new Object[] { i };
}
}
package org.lambdatarunner;
interface NullaryIntegerFunction {
void apply(Integer i);
}
package org.lambdatarunner;
class TestSpecImpl implements TestSpec {
private final NullaryIntegerFunction testRunner;
private final Datum datum;
TestSpecImpl(NullaryIntegerFunction testRunner, Datum datum) {
this.testRunner = testRunner;
this.datum = datum;
}
@Override
public void run() throws Throwable {
testRunner.apply((Integer) getDatum().values()[0]);
}
@Override
public Datum getDatum() {
return datum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment