/** * Safe version of {@link Type#format(Object)}, which checks for null input value and if so * returns a {@link FormattedItemValue} with null value properties. * * @see #format(Object) */ FormattedItemValue safeFormat(@Nullable Object value) { if (value == null) { return FormattedItemValue.NULL_VALUES; } return format(value); }
@Test public void testFormatIncompatibleTypes() { Map<DisplayData.Type, Object> invalidPairs = ImmutableMap.<DisplayData.Type, Object>builder() .put(DisplayData.Type.STRING, 1234) .put(DisplayData.Type.INTEGER, "string value") .put(DisplayData.Type.FLOAT, "string value") .put(DisplayData.Type.BOOLEAN, "string value") .put(DisplayData.Type.TIMESTAMP, "string value") .put(DisplayData.Type.DURATION, "string value") .put(DisplayData.Type.JAVA_CLASS, "string value") .build(); for (Map.Entry<DisplayData.Type, Object> pair : invalidPairs.entrySet()) { try { DisplayData.Type type = pair.getKey(); Object invalidValue = pair.getValue(); type.format(invalidValue); fail( String.format( "Expected exception not thrown for invalid %s value: %s", type, invalidValue)); } catch (ClassCastException e) { // Expected } } }
@Test public void testFormatCompatibleTypes() { Multimap<DisplayData.Type, Object> validPairs = ImmutableMultimap.<DisplayData.Type, Object>builder() .put(DisplayData.Type.INTEGER, 1234) .put(DisplayData.Type.INTEGER, 1234L) .put(DisplayData.Type.FLOAT, 123.4f) .put(DisplayData.Type.FLOAT, 123.4) .put(DisplayData.Type.FLOAT, 1234) .put(DisplayData.Type.FLOAT, 1234L) .build(); for (Map.Entry<DisplayData.Type, Object> pair : validPairs.entries()) { DisplayData.Type type = pair.getKey(); Object value = pair.getValue(); try { type.format(value); } catch (ClassCastException e) { throw new AssertionError( String.format( "Failed to format %s for DisplayData.%s", value.getClass().getSimpleName(), type), e); } } }
private static Matcher<DisplayData> hasDisplayItem( String key, DisplayData.Type type, Object value) { DisplayData.FormattedItemValue formattedValue = type.format(value); return hasDisplayItem( allOf(hasKey(key), hasType(type), hasValue(formattedValue.getLongValue()))); }
ItemSpec.Builder<T> setRawValue(@Nullable T value) { FormattedItemValue formatted = getType().safeFormat(value); return this.setValue(formatted.getLongValue()).setShortValue(formatted.getShortValue()); } }