Description
My appologies in advance if there is a way to do this, but in my search I could not find one.
It would be immensly useful if there were an @otherwise for theories. What this would do is execute for a datapoint or set of datapoints if, and only if, no theory method had a passing assume. This would allow the avoidance of a theory or theories that are basically just negations of all the other assumes.
In the example below, without the @otherwise, it would be necessary to write multiple @theory methods to have all of the paths leading to false. The other alternative would be have another set of datapoints that should all return false, but that does not allow the potential to catch possible holes in logic that are not obvious at first glance. Additionally, if the datapoints are large-volume and generated with a supplier, it could be a daunting task to make sure you catch all the "other" scenarios. Simply catching "everything else" is much easier than making sure you capture all the reverse scenarios.
Obviously this specific scenario below is not very complex, but is is just to demonstrate the purpose of @otherwise.
@RunWith(Theories.class)
public class BooleanTest {
@DataPoints
public static Object[] values = {
true, false, "true", "false", "1", "0", 1, 0, new Object(), null
};
@Theory
public void booleanTrue(Object value) {
assumeThat(value, instanceOf(Boolean.class));
assertThat(convertToBoolean(value), equalTo(value));
}
@Theory
public void stringTrue(Object value) {
assumeThat(value, instanceOf(String.class));
assumeThat((String) value, equalTo("true"));
assertThat(convertToBoolean(value), equalTo(true));
}
@Theory
public void stringOne(Object value) {
assumeThat(value, instanceOf(String.class));
assumeThat((String) value, equalTo("1"));
assertThat(convertToBoolean(value), equalTo(true));
}
@Theory
public void integerOne(Object value) {
assumeThat(value, instanceOf(Integer.class));
assumeThat((Integer) value, not(equalTo(0)));
assertThat(convertToBoolean(value), equalTo(true));
}
@Otherwise
public void allOtherCases(Object value) {
assertThat(convertToBoolean(value), equalTo(false));
}
public static boolean convertToBoolean(Object value) {
if (value instanceof Boolean) {
return ((Boolean) value).booleanValue();
} else if (value instanceof String) {
if ("true".equalsIgnoreCase((String) value)) {
return true;
} else if ("1".equalsIgnoreCase((String) value)) {
return true;
}
} else if (value instanceof Integer) {
if (((Integer)value) != 0) {
return true;
}
}
return false;
}
}