Skip to content

Instantly share code, notes, and snippets.

@jonbodner
Created February 25, 2019 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonbodner/20dabc362b75edc94a9eff87f1bb3275 to your computer and use it in GitHub Desktop.
Save jonbodner/20dabc362b75edc94a9eff87f1bb3275 to your computer and use it in GitHub Desktop.
@RunWith(Parameterized.class)
public class CalculatorTest {
@Parameters(name = "{index}: CalculatorTest({0})={1}, throws {2}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"1 + 1", 2, null},
{"1 + 1 + 1", 3, null},
{"1–1", 0, null},
{"1 * 1", 1, null},
{"1 / 1", 1, null},
{"( 1 + 1 )", 2, null},
{"+", 0, new CalculatorException("Invalid expression: +")},
{"1 1", 0, new CalculatorException("Invalid expression: 1 1")}
});
}
private final String input;
private final double expected;
private final Exception exception;
public CalculatorTest(String input, double expected, Exception exception) {
this.input = input;
this.expected = expected;
this.exception = exception;
}
@Test
public void testProcess() {
Calculator c = new CalculatorImpl();
try {
double result = c.process(input);
if (exception != null) {
fail("should have thrown an exception: " + exception);
}
// shouldn't compare doubles without a delta, because FP math isn't accurate
assertEquals(expected, result, 0.000001);
} catch (Exception e) {
if (exception == null) {
fail("should not have thrown an exception, but threw " + e);
}
if (!exception.getClass().equals(e.getClass()) || !exception.getMessage().equals(e.getMessage())) {
fail("expected exception " + exception + "; got exception " + e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment