DataSize implements Comparable<DataSize> { @JsonCreator public static DataSize valueOf(String size) throws IllegalArgumentException { requireNonNull(size, "size is null"); Preconditions.checkArgument(!size.isEmpty(), "size is empty"); Matcher matcher = PATTERN.matcher(size); if (!matcher.matches()) { throw new IllegalArgumentException("size is not a valid data size string: " + size); } double value = Double.parseDouble(matcher.group(1)); String unitString = matcher.group(2); for (Unit unit : Unit.values()) { if (unit.getUnitString().equals(unitString)) { return new DataSize(value, unit); } } throw new IllegalArgumentException("Unknown unit: " + unitString); } DataSize(double size, Unit unit); static DataSize succinctBytes(long bytes); static DataSize succinctDataSize(double size, Unit unit); long toBytes(); double getValue(); Unit getUnit(); double getValue(Unit unit); long roundTo(Unit unit); DataSize convertTo(Unit unit); DataSize convertToMostSuccinctDataSize(); @JsonValue @Override String toString(); @JsonCreator static DataSize valueOf(String size); @Override int compareTo(DataSize o); @Override boolean equals(Object o); @Override int hashCode();  }
@Test(dataProvider = "parseableValues") public void testValueOf(String string, double expectedValue, DataSize.Unit expectedUnit) { DataSize size = DataSize.valueOf(string); assertEquals(size.getUnit(), expectedUnit); assertEquals(size.getValue(), expectedValue); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "size is null") public void testValueOfRejectsNull() { DataSize.valueOf(null); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "size is empty") public void testValueOfRejectsEmptyString() { DataSize.valueOf(""); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Unknown unit: kg") public void testValueOfRejectsInvalidUnit() { DataSize.valueOf("1.234 kg"); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "size is not a valid.*") public void testValueOfRejectsInvalidNumber() { DataSize.valueOf("1.2x4 B"); }