method2testcases
stringlengths 118
6.63k
|
---|
### Question:
DecimalUtil { public static final BigDecimal min(BigDecimal one, BigDecimal other) { return (one.compareTo(other) < 0 ? one : other); } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }### Answer:
@Test public void testMin() { Assert.assertEquals(DecimalUtil.FOUR, DecimalUtil.min(DecimalUtil.FIVE, DecimalUtil.FOUR)); Assert.assertEquals(DecimalUtil.FOUR, DecimalUtil.min(DecimalUtil.FOUR, DecimalUtil.NINE)); } |
### Question:
DecimalUtil { public static final boolean greaterThanZero(BigDecimal is) { return is != null && is.compareTo(BigDecimal.ZERO) > 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }### Answer:
@Test public void testGreaterThanZero() { Assert.assertFalse(DecimalUtil.greaterThanZero(null)); Assert.assertFalse(DecimalUtil.greaterThanZero(BigDecimal.ZERO)); Assert.assertTrue(DecimalUtil.greaterThanZero(DecimalUtil.SEVEN)); } |
### Question:
DecimalUtil { public static boolean zeroOrMore(BigDecimal decimal) { return decimal != null && decimal.compareTo(BigDecimal.ZERO) >= 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }### Answer:
@Test public void testZeroOrMore() { Assert.assertFalse(DecimalUtil.zeroOrMore(null)); Assert.assertFalse(DecimalUtil.zeroOrMore(BigDecimal.valueOf(-0.01))); Assert.assertTrue(DecimalUtil.zeroOrMore(BigDecimal.ZERO)); Assert.assertTrue(DecimalUtil.zeroOrMore(BigDecimal.valueOf(0.01))); Assert.assertTrue(DecimalUtil.zeroOrMore(DecimalUtil.SEVEN)); } |
### Question:
DecimalUtil { public static final boolean lessThanZero(BigDecimal decimal) { if (decimal == null) return false; return decimal.compareTo(BigDecimal.ZERO) < 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }### Answer:
@Test public void testLessThanZero() { Assert.assertFalse(DecimalUtil.lessThanZero(null)); Assert.assertTrue(DecimalUtil.lessThanZero(BigDecimal.valueOf(-0.01))); Assert.assertFalse(DecimalUtil.lessThanZero(BigDecimal.ZERO)); Assert.assertFalse(DecimalUtil.lessThanZero(BigDecimal.valueOf(0.01))); Assert.assertTrue(DecimalUtil.lessThanZero(BigDecimal.valueOf(-7))); } |
### Question:
DecimalUtil { public static final boolean lessOrEqualtoZero(BigDecimal decimal) { if (decimal == null) return false; return decimal.compareTo(BigDecimal.ZERO) <= 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }### Answer:
@Test public void testLessOrEqualtoZero() { Assert.assertFalse(DecimalUtil.lessOrEqualtoZero(null)); Assert.assertTrue(DecimalUtil.lessOrEqualtoZero(BigDecimal.valueOf(-0.01))); Assert.assertTrue(DecimalUtil.lessOrEqualtoZero(BigDecimal.ZERO)); Assert.assertFalse(DecimalUtil.lessOrEqualtoZero(BigDecimal.valueOf(0.01))); Assert.assertTrue(DecimalUtil.lessOrEqualtoZero(BigDecimal.valueOf(-7))); } |
### Question:
DecimalUtil { public static final boolean lessOrEqual(BigDecimal decimal, int other) { return decimal.compareTo(BigDecimal.valueOf(other)) <= 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }### Answer:
@Test public void testLessOrEqual() { Assert.assertTrue(DecimalUtil.lessOrEqual(DecimalUtil.FIVE, 11)); Assert.assertFalse(DecimalUtil.lessOrEqual(DecimalUtil.FIVE, 3)); } |
### Question:
DecimalUtil { public static final BigDecimal divide(BigDecimal decimal, int by) { return decimal.divide(BigDecimal.valueOf(by)); } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }### Answer:
@Test public void testDivideBigDecimalInt() { Assert.assertEquals(BigDecimal.ZERO, DecimalUtil.divide(BigDecimal.ZERO, 3)); Assert.assertEquals(DecimalUtil.TWO, DecimalUtil.divide(DecimalUtil.EIGHT, 4)); }
@Test public void testDivideBigDecimalMathContextInt() { MathContext mc = new MathContext(1, RoundingMode.HALF_UP); Assert.assertEquals(DecimalUtil.THREE, DecimalUtil.divide(DecimalUtil.FIVE, mc, 2)); }
@Test public void testDivideBigDecimalMathContextBigDecimal() { MathContext mc = new MathContext(1, RoundingMode.HALF_UP); Assert.assertEquals(DecimalUtil.THREE, DecimalUtil.divide(DecimalUtil.FIVE, mc, DecimalUtil.TWO)); }
@Test public void testDivideIntMathContextInt() { MathContext mc = new MathContext(1, RoundingMode.HALF_UP); Assert.assertEquals(DecimalUtil.THREE, DecimalUtil.divide(5, mc, 2)); } |
### Question:
DecimalUtil { public static final BigDecimal multiply(BigDecimal decimal, int by) { return decimal.multiply(BigDecimal.valueOf(by)); } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }### Answer:
@Test public void testMultiply() { Assert.assertEquals(DecimalUtil.SIX, DecimalUtil.multiply(DecimalUtil.THREE, 2)); } |
### Question:
DecimalUtil { public static final BigDecimal valueOf(String string) { return new BigDecimal(localizeString(string)); } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }### Answer:
@Test public void testValueOf() { Assert.assertEquals(BigDecimal.ZERO, DecimalUtil.valueOf("0")); Assert.assertEquals(BigDecimal.valueOf(0.1), DecimalUtil.valueOf("0.1")); Assert.assertEquals(BigDecimal.valueOf(0.1), DecimalUtil.valueOf("0,1")); Assert.assertEquals(BigDecimal.valueOf(1000.1), DecimalUtil.valueOf("1.000,1")); Assert.assertEquals(BigDecimal.valueOf(1000.1), DecimalUtil.valueOf("1,000.1")); Assert.assertEquals(DecimalUtil.THREE, DecimalUtil.valueOf("3,")); Assert.assertEquals(BigDecimal.valueOf(0.2), DecimalUtil.valueOf(",2")); Assert.assertEquals(BigDecimal.valueOf(1000000000), DecimalUtil.valueOf("1.000.000.000")); }
@Test(expected = IllegalArgumentException.class) public void testValueOfMeerderePuntenEnKommas() { Assert.assertEquals(BigDecimal.ZERO, DecimalUtil.valueOf("0,1,2.3.4")); }
@Test(expected = IllegalArgumentException.class) public void testValueOfMeerdereKommas() { Assert.assertEquals(BigDecimal.ZERO, DecimalUtil.valueOf("0.3,4,5")); }
@Test(expected = IllegalArgumentException.class) public void testValueOfMeerderePunten() { Assert.assertEquals(BigDecimal.ZERO, DecimalUtil.valueOf("0,3.4.5")); } |
### Question:
Asserts { public static void assertNotNull(final String parameter, final Object waarde) { if (log.isDebugEnabled()) { String waardeText = String.valueOf(waarde); waardeText = waardeText.substring(0, Math.min(waardeText.length(), 16)); log.debug("Controleer dat " + parameter + " niet null is, huidige waarde: '" + waardeText + "'"); } if (waarde == null) { IllegalArgumentException exception = new IllegalArgumentException("Parameter " + parameter + " is null"); throw exception; } } static void assertNotNull(final String parameter, final Object waarde); static void assertNull(final String parameter, final Object waarde); static void assertMaxLength(String parameter, String waarde, int length); static void assertGreaterThanZero(final String parameter, long waarde); static void assertGreaterThanZero(final String parameter, int waarde); static void assertNotEmpty(String parameter, Object waarde); static void assertNotEmpty(String parameter, Collection< ? > list); static void assertEmptyCollection(String parameter, Collection< ? > list); static void assertEquals(String parameter, Object actual, Object expected); static void assertMatchesRegExp(String parameter, String value, String regexp); static void fail(String message); static void assertTrue(String message, boolean conditie); static void assertFalse(String message, boolean conditie); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testAssertNotNullMetNull() { Asserts.assertNotNull("foo", null); }
@Test public void testAssertNotNullMetNotNull() { Asserts.assertNotNull("foo", new Object()); } |
### Question:
Asserts { public static void assertNotEmpty(String parameter, Object waarde) { assertNotNull(parameter, waarde); if ("".equals(waarde.toString().trim())) { String bericht = "Parameter " + parameter + " is leeg"; throw new IllegalArgumentException(bericht); } } static void assertNotNull(final String parameter, final Object waarde); static void assertNull(final String parameter, final Object waarde); static void assertMaxLength(String parameter, String waarde, int length); static void assertGreaterThanZero(final String parameter, long waarde); static void assertGreaterThanZero(final String parameter, int waarde); static void assertNotEmpty(String parameter, Object waarde); static void assertNotEmpty(String parameter, Collection< ? > list); static void assertEmptyCollection(String parameter, Collection< ? > list); static void assertEquals(String parameter, Object actual, Object expected); static void assertMatchesRegExp(String parameter, String value, String regexp); static void fail(String message); static void assertTrue(String message, boolean conditie); static void assertFalse(String message, boolean conditie); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testAssertNotEmptyMetEmpty() { Asserts.assertNotEmpty("foo", ""); }
@Test public void testAssertNotEmptyMetNotEmpty() { Asserts.assertNotEmpty("foo", "123"); } |
### Question:
Asserts { public static void assertMatchesRegExp(String parameter, String value, String regexp) { assertNotNull(parameter, value); assertNotNull("regexp", regexp); Pattern pattern = Pattern.compile(regexp); String trimmedValue = value.trim(); Matcher matcher = pattern.matcher(trimmedValue.subSequence(0, trimmedValue.length())); if (!matcher.matches()) { if (log.isDebugEnabled()) { log.debug("Matcher waarde: " + matcher.toString()); } throw new IllegalArgumentException("De waarde '" + value + "' van parameter " + parameter + " voldoet niet aan het formaat " + regexp); } } static void assertNotNull(final String parameter, final Object waarde); static void assertNull(final String parameter, final Object waarde); static void assertMaxLength(String parameter, String waarde, int length); static void assertGreaterThanZero(final String parameter, long waarde); static void assertGreaterThanZero(final String parameter, int waarde); static void assertNotEmpty(String parameter, Object waarde); static void assertNotEmpty(String parameter, Collection< ? > list); static void assertEmptyCollection(String parameter, Collection< ? > list); static void assertEquals(String parameter, Object actual, Object expected); static void assertMatchesRegExp(String parameter, String value, String regexp); static void fail(String message); static void assertTrue(String message, boolean conditie); static void assertFalse(String message, boolean conditie); }### Answer:
@Test public void testAssertMatchesRegExp() { Asserts.assertMatchesRegExp("postcode", "1234 Aa", "[1-9][0-9]{3} ?[a-zA-Z]{2}"); Asserts.assertMatchesRegExp("postcode", "1234Aa", "[1-9][0-9]{3} ?[a-zA-Z]{2}"); Asserts.assertMatchesRegExp("postcode", " 1234 Aa ", "[1-9][0-9]{3} ?[a-zA-Z]{2}"); }
@Test(expected = IllegalArgumentException.class) public void testAssertMatchesRegExpFail1() { Asserts.assertMatchesRegExp("foo", null, "[1-9][0-9]{3} ?[a-zA-Z]{2}"); }
@Test(expected = IllegalArgumentException.class) public void testAssertMatchesRegExpFail2() { Asserts.assertMatchesRegExp("foo", "", "[1-9][0-9]{3} ?[a-zA-Z]{2}"); }
@Test(expected = IllegalArgumentException.class) public void testAssertMatchesRegExpFail3() { Asserts.assertMatchesRegExp("foo", "abc", "[1-9][0-9]{3} ?[a-zA-Z]{2}"); } |
### Question:
Dutch implements ToWords { @SuppressWarnings("all") public String toWords(long num) { if (num == 0) return ZERO; boolean negative = (num < 0); if (negative) num = -num; String s = ""; for (int group = 0; num > 0; group++) { int remdr = (int) (num % divisor[group]); num = num / divisor[group]; if (group == 1&& 1 <= num && num <= 5) { if (remdr > 0) { remdr += num * 10; num = 0; } } String t; if (remdr == 0) continue; else if (remdr == 1) t = (group == 0 || group > 2) ? lowName[1] : ""; else if (remdr < 20) t = lowName[remdr]; else if (remdr < 100) { int units = remdr % 10; int tens = remdr / 10; t = tys[tens]; if (units > 0) { t = lowName[units] + AND + t; } } else t = toWords(remdr); boolean leftPad = group > 2; boolean rightPad = group != 1; s = t + (leftPad ? " " : "") + groupName[group] + (rightPad ? " " : "") + s; } s = s.trim(); if (negative) s = MINUS + " " + s; return s; } @SuppressWarnings("all") String toWords(long num); static final String EMBEDDED_COPYRIGHT; }### Answer:
@Test public void test0() { Assert.assertEquals("nul", dutch.toWords(0)); }
@Test public void testMin1() { Assert.assertEquals("min een", dutch.toWords(-1)); }
@Test public void test1() { Assert.assertEquals("een", dutch.toWords(1)); }
@Test public void testMin10() { Assert.assertEquals("min tien", dutch.toWords(-10)); }
@Test public void test10() { Assert.assertEquals("tien", dutch.toWords(10)); }
@Test public void test21() { Assert.assertEquals("eenentwintig", dutch.toWords(21)); }
@Test public void testMin100() { Assert.assertEquals("min honderd", dutch.toWords(-100)); }
@Test public void test100() { Assert.assertEquals("honderd", dutch.toWords(100)); }
@Test public void test111() { Assert.assertEquals("honderdelf", dutch.toWords(111)); }
@Test public void testPositive1113() { Assert.assertEquals("elfhonderddertien", dutch.toWords(1113)); }
@Test public void testPositive1999() { Assert.assertEquals("negentienhonderdnegenennegentig", dutch.toWords(1999)); }
@Test public void testPositive1miljoen() { Assert.assertEquals("een miljoen", dutch.toWords(1000000)); } |
### Question:
StringUtil { public static String containsSamengesteldeLetter(String value) { if (isEmpty(value)) return " "; String naam = value.toUpperCase(); for (String letter : SAMENGESTELDE_LETTERS) { if (naam.startsWith(letter)) { return letter; } } return String.valueOf(value.charAt(0)).toUpperCase(); } private StringUtil(); static boolean checkMatchesRegExp(String parameter, String value, String regexp); @Deprecated() static String stripHighAscii(String tekst); static Integer getFirstNumberSequence(String tekst); static String getLastCharacter(String string); static boolean isNumeric(String string); static boolean isEmail(String string); static boolean isIpAdres(String string); static boolean isDecimal(String string); static String firstCharUppercase(String name); static String firstLetterUppercase(String name); static String onlyFirstCharUppercase(String name); static String containsSamengesteldeLetter(String value); static String firstCharUppercaseOfEachWord(String sentence); static String firstCharUppercaseOnlyIfOneWordAndStartWithLowercase(String sentence); static String puntSeperated(String sentence); static boolean isEmpty(String string); static boolean areAllEmpty(String... strings); static boolean areAllNotEmpty(String... strings); static boolean isEmpty(Object object); static boolean isNotEmpty(String string); static boolean isNotEmpty(Object string); static String truncate(String source, int maxLength, String cutoffReplacement); static String escapeString(String value); static String escapeForJavascriptString(String value); static String valueOrEmptyIfNull(Object text); static String valueOrAlternativeIfNull(Object text, String alternative); static String valueOrAlternativeIfEmpty(Object text, String alternative); static String repeatString(String src, int repeat); static String maakTekenSeparatedString(Collection< ? extends Object> list, String teken); static String maakCommaSeparatedString(Collection< ? extends Object> list); static String maakCommaSeparatedString(Collection< ? extends Object> list,
String defaultByEmptyList); static String toString(Collection<T> list, String token, String defaultString); static String toString(Collection<T> list, String defaultString,
StringConverter< ? super T> converter); static String maakPuntSeparatedString(Collection< ? extends Object> list); static String verwijderCijfers(String input); static String voegVoorloopnullenToe(String str, int length); static String voegVoorloopnullenToe(int i, int length); static String kapAfOfVoegSpatiesToe(String str, int length); static String kapAfOfVoegNullenToe(Integer i, int length); static String kapAfOfVoegNullenToe(String str, int length); static String verwijderVoorloopnullen(String str); static int countOccurances(String org, char character); static String join(Collection<String> strings, String separator); static boolean startsWithIgnoreCase(String string1, String string2); @Deprecated static String getClassName(Class< ? > class1); static String getFirstWord(String input); static boolean containsOracleWildcard(String string); static String wildcardToRegex(String wildcard); static String convertCamelCase(String camelCase); static String convertCamelCaseFirstCharUpperCase(String camelCase); static String stripHtmlTags(String html); static boolean equalOrBothNull(String str1, String str2); static boolean equalOrBothEmpty(String a, String b); static String genereerVoorletters(String voornamen); static String hexEncode(byte[] aInput); static boolean containsStringStartingWith(List<String> list, String prefix); static String nullOrStringValue(Object value); static String emptyOrStringValue(Object value); static String firstCharLowercase(String name); static String spaties(int aantal); static String createValidFileName(String filename); static final String[] SAMENGESTELDE_LETTERS; }### Answer:
@Test public void samenGesteldeLetter() { String naam = "IJsbrand"; String naam1 = "Pietje"; assertEquals("IJ", StringUtil.containsSamengesteldeLetter(naam)); assertEquals("P", StringUtil.containsSamengesteldeLetter(naam1)); } |
### Question:
SpringBootExample implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(SpringBootExample.class, args); } static void main(String[] args); @Override void run(String... args); }### Answer:
@Test public void shouldExecuteMainWithoutExceptions() { SpringBootExample.main(new String[0]); } |
### Question:
WritableMapConfigurationSource extends MapConfigurationSource implements WritableConfigurationSource { @Override public OptionalValue<String> removeValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); return source.containsKey(key) ? present(source.remove(key)) : absent(); } WritableMapConfigurationSource(Map<String, String> source); @Override void setValue(String key, String value, Map<String, String> attributes); @Override OptionalValue<String> removeValue(String key, Map<String, String> attributes); }### Answer:
@Test public void shouldRemoveValue() { Map<String, String> map = new HashMap<>(); map.put("key", "value"); WritableConfigurationSource mapConfigurationSource = new WritableMapConfigurationSource(map); mapConfigurationSource.removeValue("key", null); assertThat(mapConfigurationSource.getValue("key", null).isPresent()).isFalse(); } |
### Question:
PropertiesConfigurationSource implements IterableConfigurationSource { @Override public Iterable<ConfigurationEntry> getAllConfigurationEntries() { Map<String, String> map = source.entrySet().stream() .filter(e -> e.getValue() instanceof String) .collect(toMap(Object::toString, e -> (String) e.getValue())); return new MapIterable(map); } PropertiesConfigurationSource(Properties source); PropertiesConfigurationSource(String propertyFile); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override Iterable<ConfigurationEntry> getAllConfigurationEntries(); }### Answer:
@Test public void shouldLoadPropertiesFromFile() { PropertiesConfigurationSource source = new PropertiesConfigurationSource(file.getAbsolutePath()); assertThat(source.getAllConfigurationEntries().iterator()).isEmpty(); } |
### Question:
PatternConverter implements TypeConverter<Pattern> { @Override public Pattern fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); try { return (value == null) ? null : Pattern.compile(value); } catch (PatternSyntaxException e) { throw new IllegalArgumentException("Unable to convert to a Pattern: " + value, e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Pattern fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Pattern value, Map<String, String> attributes); }### Answer:
@Test public void shouldConvertFromString() { Pattern pattern = Pattern.compile(".*"); Pattern value = converter.fromString(Pattern.class, ".*", null); assertThat(value.pattern()).isEqualTo(pattern.pattern()); }
@Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValue() { String value = "{"; assertThatThrownBy(() -> converter.fromString(Pattern.class, value, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert to a Pattern:"); } |
### Question:
PatternConverter implements TypeConverter<Pattern> { @Override public String toString(Type type, Pattern value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return Objects.toString(value, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Pattern fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Pattern value, Map<String, String> attributes); }### Answer:
@Test public void shouldConvertToString() { Pattern pattern = Pattern.compile("123.*"); String asString = converter.toString(Pattern.class, pattern, null); assertThat(asString).isEqualTo(pattern.toString()); } |
### Question:
PatternConverter implements TypeConverter<Pattern> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Pattern.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Pattern fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Pattern value, Map<String, String> attributes); }### Answer:
@Test public void shouldAcceptType() { Type type = Pattern.class; boolean isApplicable = converter.isApplicable(type, null); assertThat(isApplicable).isTrue(); }
@Test public void shouldNotAcceptUnknownType() { boolean isApplicable = converter.isApplicable(mock(Type.class), null); assertThat(isApplicable).isFalse(); } |
### Question:
ObjectBuilder { ObjectBuilder beginList() { return beginList(new ArrayList<>()); } }### Answer:
@Test public void shouldFailInCaseEndingObjectWhenArrayWasBegun() { assertThatThrowExceptionOfType( new ObjectBuilder().beginList()::endMap, IllegalStateException.class); } |
### Question:
ObjectBuilder { ObjectBuilder beginMap() { return beginMap(new LinkedHashMap<>()); } }### Answer:
@Test public void shouldFailInCaseEndingArrayWhenObjectWasBegun() { assertThatThrowExceptionOfType( new ObjectBuilder().beginMap()::endList, IllegalStateException.class); } |
### Question:
TypeConverterUtils { static int notEscapedIndexOf(CharSequence value, int startPos, char character) { Objects.requireNonNull(value, "value must not be null"); char prev = 0xffff; for (int i = max(startPos, 0), len = value.length(); i < len; i++) { char current = value.charAt(i); if (current == character) { if (prev == ESCAPE_CHAR) { int m = 1; int l = i - 2; while (l >= 0 && value.charAt(l) == ESCAPE_CHAR) { l--; m++; } if (m % 2 == 0) { return i; } } else { return i; } } prev = current; } return NOT_FOUND; } private TypeConverterUtils(); }### Answer:
@Test public void shouldProperlyReturnNotEscapedIndexOf() { assertThat(TypeConverterUtils.notEscapedIndexOf("abcb", 0, 'b')).isEqualTo(1); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\bcb", 0, 'b')).isEqualTo(4); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\b\\\\bcb", 0, 'b')).isEqualTo(5); }
@Test public void shouldProperlyReturnNotEscapedIndexOfMultiArgs() { assertThat(TypeConverterUtils.notEscapedIndexOf("abcb", 0, 'b', 'a')).isEqualTo(0); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\bcb", 0, 'b', 'c')).isEqualTo(3); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\b\\\\cb", 0, 'b', 'c')).isEqualTo(5); } |
### Question:
JaxbConverter implements TypeConverter<T> { @Override public T fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (isBlank(value)) { return null; } @SuppressWarnings("unchecked") Class<T> targetClazz = (Class<T>) type; JaxbPool jaxbPool = getJaxbPool(targetClazz); try (Handle<Unmarshaller> handle = jaxbPool.borrowUnmarshaller()) { return targetClazz.cast(handle.get().unmarshal(new ByteArrayInputStream(value.getBytes()))); } catch (JAXBException e) { throw new IllegalArgumentException("Unable to convert xml to " + targetClazz + " using jaxb", e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer:
@Test public void shouldReturnNullObjectForBlankXML() { String resource = " "; XmlRootConfiguration01 xmlRootConfiguration01 = (XmlRootConfiguration01) jaxbTypeConverter.fromString(XmlRootConfiguration01.class, resource, null); assertThat(xmlRootConfiguration01).isNull(); }
@Test public void shouldReturnNullObjectForNullXML() { String resource = null; XmlRootConfiguration01 xmlRootConfiguration01 = (XmlRootConfiguration01) jaxbTypeConverter.fromString(XmlRootConfiguration01.class, resource, null); assertThat(xmlRootConfiguration01).isNull(); }
@Test public void shouldFailValidationWhenReadingXMLNotCompliantWithTheSchema() { String resource = loadXml("/JaxbTypeAdapterTest/XmlRootConfiguration01.invalid.xml"); assertThatThrownBy(() -> jaxbTypeConverter.fromString(XmlRootConfiguration01.class, resource, null)) .isInstanceOf(IllegalArgumentException.class); }
@Test public void shouldReturnProperPojoForValidXML() { String resource = loadXml("/JaxbTypeAdapterTest/XmlRootConfiguration01.xml"); XmlRootConfiguration01 config01 = (XmlRootConfiguration01) jaxbTypeConverter.fromString(XmlRootConfiguration01.class, resource, null); assertThat(config01.getConfigurationName()).isEqualTo("ROOT01"); assertThat(config01.getXmlSubConfigurations()).hasSize(2); assertThat(config01.getXmlSubConfigurations().get(0).getVersion()).isEqualTo(1); assertThat(config01.getXmlSubConfigurations().get(1).getVersion()).isEqualTo(2); }
@Test public void shouldReturnProperPojoForSecondValidXML() { String resource = loadXml("/JaxbTypeAdapterTest/XmlRootConfiguration02.xml"); XmlRootConfiguration02 config01 = (XmlRootConfiguration02) jaxbTypeConverter.fromString(XmlRootConfiguration02.class, resource, null); assertThat(config01.getConfigurationName()).isEqualTo("ROOT02"); assertThat(config01.getXmlSubConfigurations()).hasSize(2); assertThat(config01.getXmlSubConfigurations().get(0).getVersion()).isEqualTo(3); assertThat(config01.getXmlSubConfigurations().get(1).getVersion()).isEqualTo(4); } |
### Question:
PeriodConverter implements TypeConverter<Period> { @Override public Period fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); try { return value == null ? null : Period.parse(value); } catch (DateTimeParseException e) { throw new IllegalArgumentException(format("Unable to convert to a Period: %s", value), e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Period fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Period value, Map<String, String> attributes); }### Answer:
@Test public void shouldConvertFromString() { Period period = Period.ofDays(123); Period readPeriod = converter.fromString(Period.class, "P123D", null); assertThat(readPeriod).isEqualTo(period); }
@Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValue() { String toConvert = "XXXXX"; assertThatThrownBy(() -> converter.fromString(Period.class, toConvert, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert to a Period: XXXXX"); } |
### Question:
PeriodConverter implements TypeConverter<Period> { @Override public String toString(Type type, Period value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return Objects.toString(value, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Period fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Period value, Map<String, String> attributes); }### Answer:
@Test public void shouldConvertToString() { Period period = Period.ofDays(123); String asString = converter.toString(Period.class, period, null); assertThat(asString).isEqualTo("P123D"); } |
### Question:
PeriodConverter implements TypeConverter<Period> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Period.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Period fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Period value, Map<String, String> attributes); }### Answer:
@Test public void shouldAcceptPeriodType() { Type type = Period.class; boolean isApplicable = converter.isApplicable(type, null); assertThat(isApplicable).isTrue(); }
@Test public void shouldNotAcceptUnknownType() { boolean isApplicable = converter.isApplicable(mock(Type.class), null); assertThat(isApplicable).isFalse(); } |
### Question:
LongConverter extends AbstractNumberConverter<Long> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Long.class, Long.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableWhenLongType() { Type type = Long.class; boolean applicable = longTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotLongType() { Type type = Boolean.class; boolean applicable = longTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> longTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
OffsetDateTimeConverter extends AbstractTemporalAccessorConverter<OffsetDateTime> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && OffsetDateTime.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableWhenOffsetDateTimeType() { Type type = OffsetDateTime.class; boolean applicable = offsetDateTimeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotOffsetDateTimeType() { Type type = Boolean.class; boolean applicable = offsetDateTimeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> offsetDateTimeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
CharacterConverter implements TypeConverter<Character> { @Override public Character fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null || value.isEmpty()) { return null; } if (value.length() == 1) { return value.charAt(0); } if (value.charAt(0) == '\\') { String unescapedValue; try { unescapedValue = unescapeJava(value); } catch (RuntimeException e) { throw new IllegalArgumentException(format("Unable to convert to a Character: %s", value), e); } if (unescapedValue.length() == 1) { return unescapedValue.charAt(0); } } throw new IllegalArgumentException(format("Unable to convert to a Character: %s", value)); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Character fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Character value, Map<String, String> attributes); }### Answer:
@Test public void shouldReadValuesFromStringWhenNotUnescaping() { String stringValue = "A"; Character value = converter.fromString(Character.class, stringValue, null); assertThat(value).isEqualTo('A'); }
@Test public void shouldReadValuesFromStringWhenUnescaping() { String stringValue = "\\u0080"; Character value = converter.fromString(Character.class, stringValue, null); assertThat(value).isEqualTo('\u0080'); }
@Test public void shouldThrowExceptionWhenReadingIllegalValuesFromString() { String stringValue = "longer then just on character string"; assertThrows(IllegalArgumentException.class, () -> converter.fromString(Character.class, stringValue, null), "Unable to convert to a Character: " + stringValue ); }
@Test public void shouldConvertToNullFromEmptyString() { String stringValue = ""; Character value = converter.fromString(Character.class, stringValue, null); assertThat(value).isNull(); }
@Test public void shouldEscapedString() { String invalidEncodedCharacter = "\\u001"; assertThrows(IllegalArgumentException.class, () -> converter.fromString(Character.class, invalidEncodedCharacter, null), "Unable to convert to a Character: " + invalidEncodedCharacter ); } |
### Question:
CharacterConverter implements TypeConverter<Character> { @Override public String toString(Type type, Character value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : escapeJava(value.toString()); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Character fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Character value, Map<String, String> attributes); }### Answer:
@Test public void shouldWriteValueAsString() { Character value = 'A'; String asString = converter.toString(Character.class, value, null); assertThat(asString).isEqualTo("A"); }
@Test public void shouldConvertToNullFromNull() { Character value = null; String asString = converter.toString(Character.class, value, null); assertThat(asString).isNull(); }
@Test public void shouldUnescapeEscapedString() { Character value = '\u0080'; String asString = converter.toString(Character.class, value, null); assertThat(asString).isEqualTo("\\u0080"); } |
### Question:
CharacterConverter implements TypeConverter<Character> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && (Character.class.isAssignableFrom((Class<?>) type) || Character.TYPE.isAssignableFrom((Class<?>) type)); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Character fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Character value, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableToCharacter() { boolean applicable = converter.isApplicable(Character.class, null); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableToNonCharacter() { boolean applicable = converter.isApplicable(Object.class, null); assertThat(applicable).isFalse(); } |
### Question:
DurationConverter implements TypeConverter<Duration> { @Override public Duration fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); String format = (attributes == null) ? null : attributes.get(FORMAT); if (format != null) { try { SimpleDateFormat dateFormat = getDateFormat(format); LocalDateTime localDateTime = LocalDateTime.ofInstant(dateFormat.parse(value).toInstant(), ZoneId.systemDefault()); return Duration.between(Instant.EPOCH, localDateTime.toInstant(ZoneOffset.ofTotalSeconds(0))); } catch (ParseException e) { throw new IllegalArgumentException(format("Unable to convert to Duration: %s. " + "The value doesn't match specified format '%s'.", value, format), e); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(format("Unable to convert to Duration: %s. " + "Invalid format: '%s'", value, format), e); } } try { return (value == null) ? null : Duration.parse(value); } catch (DateTimeParseException e) { throw new IllegalArgumentException(format("Unable to convert to Duration: %s", value), e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Duration fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Duration value, Map<String, String> attributes); static final String FORMAT; }### Answer:
@Test public void shouldConvertFromStringWhenFormatNotSpecified() { Duration duration = Duration.ofMillis(1260535L); Duration readDuration = converter.fromString(Duration.class, "PT21M0.535S", null); assertThat(readDuration).isEqualTo(duration); }
@Test public void shouldConvertFromStringWhenFormatSpecified() { Duration duration = Duration.ofMillis(600000L); String format = "HH:mm:ss"; Map<String, String> attributes = singletonMap("format", format); Duration readDuration = converter.fromString(Duration.class, "00:10:00", attributes); assertThat(readDuration).isEqualTo(duration); }
@Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValueString() { String durationInString = "invalid value string"; assertThatThrownBy(() -> converter.fromString(Duration.class, durationInString, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert to Duration"); }
@Test public void shouldThrowExceptionWhenConvertingFromStringWithFormatAndWrongValueString() { String durationInString = "invalid value string"; String format = "H:i:s"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> converter.fromString(Duration.class, durationInString, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert to Duration"); }
@Test public void shouldThrowExceptionWhenConvertingFromStringWithFormatAndWrongValue() { String durationInString = "a wrong duration"; String format = "HH:mm:ss"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> converter.fromString(Duration.class, durationInString, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert to Duration"); } |
### Question:
DurationConverter implements TypeConverter<Duration> { @Override public String toString(Type type, Duration value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } String format = (attributes == null) ? null : attributes.get(FORMAT); if (format != null) { try { return formatDuration(value.toMillis(), format); } catch (DateTimeException e) { throw new IllegalArgumentException( "Unable to convert Duration to String. Error occurred during printing.", e); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(format( "Unable to convert Duration to String. Invalid duration value: %s", value), e); } } return value.toString(); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Duration fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Duration value, Map<String, String> attributes); static final String FORMAT; }### Answer:
@Test public void shouldConvertToStringWhenFormatNotSpecified() { Duration duration = Duration.ofMillis(1260535L); String asString = converter.toString(Duration.class, duration, null); assertThat(asString).isEqualTo("PT21M0.535S"); }
@Test public void shouldConvertToStringWhenFormatSpecified() { Duration duration = Duration.ofHours(1).plusMinutes(10).plusSeconds(20); String format = "HH:mm:ss"; Map<String, String> attributes = singletonMap("format", format); String asString = converter.toString(Duration.class, duration, attributes); assertThat(asString).isEqualTo("01:10:20"); }
@Test public void shouldReturnNullWhenConvertingToStringAndValueToConvertIsNull() { String converted = converter.toString(Duration.class, null, null); assertThat(converted).isNull(); }
@Test public void shouldThrowExceptionWhenConvertingToStringWithFormatAndWrongValue() { Duration duration = Duration.ofMillis(-600000L); String format = "HH:mm:ss"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> converter.toString(Duration.class, duration, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert Duration to String. Invalid duration value:"); } |
### Question:
DurationConverter implements TypeConverter<Duration> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Duration.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Duration fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Duration value, Map<String, String> attributes); static final String FORMAT; }### Answer:
@Test public void shouldAcceptReadableDurationType() { Type type = Duration.class; boolean isApplicable = converter.isApplicable(type, null); assertThat(isApplicable).isTrue(); }
@Test public void shouldNotAcceptUnknownType() { boolean isApplicable = converter.isApplicable(mock(Type.class), null); assertThat(isApplicable).isFalse(); } |
### Question:
ByteConverter extends AbstractNumberConverter<Byte> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Byte.class, Byte.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableWhenByteType() { Type type = Byte.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotByteType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
LocalDateTimeConverter extends AbstractTemporalAccessorConverter<LocalDateTime> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && LocalDateTime.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableWhenLocalDateTimeType() { Type type = LocalDateTime.class; boolean applicable = localDateTimeTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotLocalDateTimeType() { Type type = Boolean.class; boolean applicable = localDateTimeTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> localDateTimeTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
BigDecimalConverter extends AbstractNumberConverter<BigDecimal> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, BigDecimal.class, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableToBigDecimal() { boolean applicable = converter.isApplicable(BigDecimal.class, null); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableToNonBigDecimal() { boolean applicable = converter.isApplicable(Object.class, null); assertThat(applicable).isFalse(); } |
### Question:
IntegerConverter extends AbstractNumberConverter<Integer> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Integer.class, Integer.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableWhenIntegerType() { Type type = Integer.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotIntegerType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
DoubleConverter extends AbstractNumberConverter<Double> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Double.class, Double.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableWhenDoubleType() { Type type = Double.class; boolean applicable = doubleTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotDoubleType() { Type type = Boolean.class; boolean applicable = doubleTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> doubleTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
CurrencyConverter implements TypeConverter<Currency> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Currency.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Currency fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Currency value, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableWhenCurrencyType() { Type type = Currency.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotCurrencyType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenIsApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
YamlConverter implements TypeConverter<T> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); String converter = (attributes == null) ? null : attributes.get(CONVERTER); return ignoreConverterAttribute || Objects.equals(converter, YAML); } YamlConverter(); YamlConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer:
@Test void shouldThrowExceptionWhenTypeIsNullAndIsApplicable() { assertThatThrownBy(() -> typeConverter.isApplicable(null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
CurrencyConverter implements TypeConverter<Currency> { @Override public String toString(Type type, Currency value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : value.getCurrencyCode(); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Currency fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Currency value, Map<String, String> attributes); }### Answer:
@Test public void shouldConvertToString() { Currency toConvert = Currency.getInstance("USD"); String converted = converter.toString(Currency.class, toConvert, emptyMap()); assertThat(converted).isEqualTo("USD"); }
@Test public void shouldReturnNullWhenToStringAndValueIsNull() { String converted = converter.toString(Currency.class, null, emptyMap()); assertThat(converted).isNull(); }
@Test public void shouldThrowExceptionWhenToStringAndTypeIsNull() { Currency toConvert = Currency.getInstance("USD"); assertThatThrownBy(() -> converter.toString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
CurrencyConverter implements TypeConverter<Currency> { @Override public Currency fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : Currency.getInstance(value); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Currency fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Currency value, Map<String, String> attributes); }### Answer:
@Test public void shouldConvertFromString() { String toConvert = "USD"; Currency converted = converter.fromString(Currency.class, toConvert, emptyMap()); assertThat(converted).isEqualTo(Currency.getInstance("USD")); }
@Test public void shouldThrowExceptionWhenInvalidFormat() { String toConvert = "invalid"; assertThatThrownBy(() -> converter.fromString(Currency.class, toConvert, emptyMap())) .isExactlyInstanceOf(IllegalArgumentException.class); }
@Test public void shouldReturnNullWhenFromStringAndValueIsNull() { Currency converted = converter.fromString(Currency.class, null, emptyMap()); assertThat(converted).isNull(); }
@Test public void shouldThrowExceptionWhenFromStringAndTypeIsNull() { String toConvert = "USD"; assertThatThrownBy(() -> converter.fromString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
BooleanConverter implements TypeConverter<Boolean> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && (Boolean.class.isAssignableFrom((Class<?>) type) || Boolean.TYPE.isAssignableFrom((Class<?>) type)); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Boolean fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Boolean value, Map<String, String> attributes); static final String FORMAT; }### Answer:
@Test public void shouldBeApplicableWhenBooleanType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotBooleanType() { Type type = Integer.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
YamlConverter implements TypeConverter<T> { @Override public T fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { JavaType javaType = TypeFactory.defaultInstance().constructType(type); ObjectReader objectReader = objectMapper.readerFor(javaType); return objectReader.readValue(value); } catch (IOException e) { throw new IllegalStateException(e); } } YamlConverter(); YamlConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer:
@Test void shouldConvertFromString() { String toConvert = "" + "integer: 1\n" + "string: test-1\n"; TestClass converted = typeConverter.fromString(TestClass.class, toConvert, null); assertThat(converted).isEqualTo(new TestClass(1, "test-1")); }
@Test void shouldConvertCollectionFromString() { String toConvert = "" + "- integer: 1\n" + " string: test-1\n" + "- integer: 2\n" + " string: test-2\n"; TypeConverter<List<TestClass>> typeConverter = new YamlConverter<>(); Collection<TestClass> converted = typeConverter.fromString(parameterize(Collection.class, TestClass.class), toConvert, null); assertThat(converted) .hasSize(2) .containsSequence( new TestClass(1, "test-1"), new TestClass(2, "test-2")); }
@Test void shouldConvertMapFromString() { String toConvert = "" + "first:\n" + " integer: 1\n" + " string: test-1\n" + "second:\n" + " integer: 2\n" + " string: test-2\n"; TypeConverter<Map<String, TestClass>> typeConverter = new YamlConverter<>(); Map<String, TestClass> converted = typeConverter.fromString(parameterize(Map.class, String.class, TestClass.class), toConvert, null); assertThat(converted) .hasSize(2) .containsEntry("first", new TestClass(1, "test-1")) .containsEntry("second", new TestClass(2, "test-2")); }
@Test void shouldReturnNullWhenFromStringAndValueIsNull() { TestClass converted = typeConverter.fromString(TestClass.class, null, null); assertThat(converted).isNull(); }
@Test void shouldThrowExceptionWhenImproperYamlFormat() { String toConvert = "" + "<integer>1</integer>" + "<string>test-1</string>"; assertThatThrownBy(() -> typeConverter.fromString(TestClass.class, toConvert, null)); }
@Test void shouldThrowExceptionWhenTypeIsNullAndFromString() { assertThatThrownBy(() -> typeConverter.fromString(null, null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
BooleanConverter implements TypeConverter<Boolean> { @Override public String toString(Type type, Boolean value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (attributes != null && attributes.containsKey(FORMAT)) { String format = attributes.get(FORMAT); Pair<String, String> values = cache.computeIfAbsent(format, this::getValues); return value ? values.getLeft() : values.getRight(); } else { return Objects.toString(value, null); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Boolean fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Boolean value, Map<String, String> attributes); static final String FORMAT; }### Answer:
@Test public void shouldConvertToStringWhenFormatNotSpecifiedAndTrue() { Boolean b = true; String converted = converter.toString(Boolean.class, b, emptyMap()); assertThat(converted).isEqualTo("true"); }
@Test public void shouldConvertToStringWhenFormatNotSpecifiedAndFalse() { Boolean b = false; String converted = converter.toString(Boolean.class, b, emptyMap()); assertThat(converted).isEqualTo("false"); }
@Test public void shouldConvertToStringWhenFormatSpecifiedAndTrue() { Boolean b = true; String format = "yes/no"; Map<String, String> attributes = singletonMap("format", format); String converted = converter.toString(Boolean.class, b, attributes); assertThat(converted).isEqualTo("yes"); }
@Test public void shouldConvertToStringWhenFormatSpecifiedAndFalse() { Boolean b = false; String format = "yes/no"; Map<String, String> attributes = singletonMap("format", format); String converted = converter.toString(Boolean.class, b, attributes); assertThat(converted).isEqualTo("no"); }
@Test public void shouldReturnNullWhenConvertingToStringAndValueToConvertIsNull() { String converted = converter.toString(Boolean.class, null, emptyMap()); assertThat(converted).isNull(); }
@Test public void shouldThrowExceptionWhenConvertingToStringAndWrongFormat() { Boolean toConvert = true; String format = "wrong format"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> converter.toString(Boolean.class, toConvert, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageEndingWith("Invalid 'format' meta-attribute value, it must contain '/' separator character. Provided value is 'wrong format'."); }
@Test public void shouldThrowExceptionWhenConvertingToStringAndTypeIsNull() { Boolean b = true; assertThatThrownBy(() -> converter.toString(null, b, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
InstantConverter extends AbstractTemporalAccessorConverter<Instant> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Instant.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String toString(Type type, Instant value, Map<String, String> attributes); static final String ZONE; }### Answer:
@Test public void shouldBeApplicableWhenInstantType() { Type type = Instant.class; boolean applicable = instantConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotInstantType() { Type type = Boolean.class; boolean applicable = instantConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> instantConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
InstantConverter extends AbstractTemporalAccessorConverter<Instant> { @Override public String toString(Type type, Instant value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } String format = null; ZoneId zoneId = DEFAULT_ZONE; if (attributes != null) { format = attributes.get(FORMAT); String zone = attributes.get(ZONE); if (ZoneId.getAvailableZoneIds().contains(zone)) { zoneId = ZoneId.of(zone); } } try { return format == null ? value.toString() : getFormatterForPattern(format).withZone(zoneId).format(value); } catch (DateTimeException e) { throw new IllegalArgumentException(format("Unable to convert %s to String. ", getSimpleClassName(type)) + "Error occurred during printing.", e); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(format("Unable to convert %s to String. " + "Invalid format: '%s'", getSimpleClassName(type), format), e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String toString(Type type, Instant value, Map<String, String> attributes); static final String ZONE; }### Answer:
@Test public void shouldConvertToStringWhenFormatNotSpecified() { Instant toConvert = Instant.EPOCH; String converted = instantConverter.toString(Instant.class, toConvert, emptyMap()); assertThat(converted).isEqualTo("1970-01-01T00:00:00Z"); }
@Test public void shouldConvertToStringWhenFormatSpecifiedAndDefaultZone() { Instant toConvert = Instant.EPOCH; String format = "yyyy MM dd HH:mm"; Map<String, String> attributes = singletonMap("format", format); String converted = instantConverter.toString(Instant.class, toConvert, attributes); assertThat(converted).isEqualTo("1969 12 31 18:00"); }
@Test public void shouldConvertToStringWhenFormatAndZoneSpecified() { Instant toConvert = Instant.EPOCH; String format = "yyyy MM dd HH:mm"; Map<String, String> attributes = new HashMap<>(); attributes.put("format", format); attributes.put("zone", "Europe/London"); String converted = instantConverter.toString(Instant.class, toConvert, attributes); assertThat(converted).isEqualTo("1970 01 01 01:00"); }
@Test public void shouldConvertToStringWhenFormatSpecifiedAndWrongZone() { Instant toConvert = Instant.EPOCH; String format = "yyyy MM dd HH:mm"; Map<String, String> attributes = new HashMap<>(); attributes.put("zone", "null"); attributes.put("format", format); String converted = instantConverter.toString(Instant.class, toConvert, attributes); assertThat(converted).isEqualTo("1969 12 31 18:00"); }
@Test public void shouldReturnNullWhenConvertingToStringAndValueToConvertIsNull() { String converted = instantConverter.toString(Instant.class, null, emptyMap()); assertThat(converted).isNull(); }
@Test public void shouldThrowExceptionWhenConvertingToStringAndWrongFormat() { Instant toConvert = Instant.EPOCH; String format = "invalid format"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> instantConverter.toString(Instant.class, toConvert, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert Instant to String. Invalid format: 'invalid format'"); }
@Test public void shouldThrowExceptionWhenConvertingToStringAndTypeIsNull() { Instant toConvert = Instant.EPOCH; assertThatThrownBy(() -> instantConverter.toString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
@Test public void shouldThrowExceptionWhenConvertingFromStringAndTypeIsNull() { Instant toConvert = Instant.EPOCH; assertThatThrownBy(() -> instantConverter.toString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
StringConverter implements TypeConverter<String> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && String.class.isAssignableFrom((Class<?>) type); } StringConverter(boolean escape); StringConverter(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, String value, Map<String, String> attributes); static final String ESCAPE; }### Answer:
@Test public void shouldBeApplicableWhenStringType() { Type type = String.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotStringType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } |
### Question:
StringConverter implements TypeConverter<String> { @Override public String fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return shouldEscape(attributes) ? unescapeJava(value) : value; } StringConverter(boolean escape); StringConverter(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, String value, Map<String, String> attributes); static final String ESCAPE; }### Answer:
@Test public void shouldConvertFromStringWhenFormatNotSpecified() { String in = "One\\\\Two"; String expected = "One\\Two"; String out = converter.fromString(String.class, in, null); assertThat(out).isEqualTo(expected); }
@Test public void shouldConvertFromStringWhenFormatSpecifiedAndFalse() { String in = "One\\\\Two"; String escape = "false"; Map<String, String> attributes = singletonMap("escape", escape); String out = converter.fromString(String.class, in, attributes); assertThat(out).isEqualTo(in); }
@Test public void shouldConvertFromStringWhenFormatSpecifiedAndTrue() { String in = "One\\\\Two"; String escape = "true"; Map<String, String> attributes = singletonMap("escape", escape); String out = converter.fromString(String.class, in, attributes); assertThat(out).isEqualTo("One\\Two"); }
@Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongEscapeValue() { String in = "One\\Two"; String escape = "wrong value"; Map<String, String> attributes = singletonMap("escape", escape); assertThatThrownBy(() -> converter.fromString(String.class, in, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageEndingWith("Invalid 'escape' meta-attribute value, it must be either 'true' or 'false', but 'wrong value' is provided."); } |
### Question:
GenericsExample { public static void main(String[] args) { new GenericsExample().run(); } static void main(String[] args); }### Answer:
@Test public void shouldExecuteMainWithoutExceptions() { GenericsExample.main(new String[0]); } |
### Question:
StringConverter implements TypeConverter<String> { @Override public String toString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return shouldEscape(attributes) ? escapeJava(value) : value; } StringConverter(boolean escape); StringConverter(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, String value, Map<String, String> attributes); static final String ESCAPE; }### Answer:
@Test public void shouldConvertToStringWhenFormatNotSpecified() { String in = "One\\Two"; String expected = "One\\\\Two"; String out = converter.toString(String.class, in, null); assertThat(out).isEqualTo(expected); }
@Test public void shouldConvertToStringWhenFormatSpecifiedAndFalse() { String in = "One\\Two"; String escape = "false"; Map<String, String> attributes = singletonMap(ESCAPE, escape); String out = converter.toString(String.class, in, attributes); assertThat(out).isEqualTo(in); }
@Test public void shouldConvertToStringWhenFormatSpecifiedAndTrue() { String in = "One\\Two"; String escape = "true"; Map<String, String> attributes = singletonMap(ESCAPE, escape); String out = converter.toString(String.class, in, attributes); assertThat(out).isEqualTo("One\\\\Two"); }
@Test public void shouldThrowExceptionWhenConvertingToStringAndWrongEscapeValue() { String in = "One\\Two"; String escape = "wrong value"; Map<String, String> attributes = singletonMap(ESCAPE, escape); assertThatThrownBy(() -> converter.toString(String.class, in, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageEndingWith("Invalid 'escape' meta-attribute value, it must be either 'true' or 'false', but 'wrong value' is provided."); } |
### Question:
JsonLikeConverter implements TypeConverter<Object> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (parameterizedType.getRawType() instanceof Class) { Class<?> rawType = (Class<?>) parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (List.class.isAssignableFrom(rawType) && actualTypeArguments.length == 1) { Type itemType = actualTypeArguments[0]; return isApplicable(itemType, attributes) || innerTypeConverter.isApplicable(itemType, attributes); } else if (Map.class.isAssignableFrom(rawType) && actualTypeArguments.length == 2) { Type keyType = actualTypeArguments[0]; Type valueType = actualTypeArguments[1]; return (isApplicable(keyType, attributes) || innerTypeConverter.isApplicable(keyType, attributes)) && (isApplicable(valueType, attributes) || innerTypeConverter.isApplicable(valueType, attributes)); } } } return false; } JsonLikeConverter(TypeConverter<?> innerTypeConverter); @SuppressWarnings("unchecked") JsonLikeConverter(TypeConverter<?> innerTypeConverter, boolean compactMode); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Object fromString(Type type, String value, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override String toString(Type type, Object value, Map<String, String> attributes); static final String FORMAT; static final String COMPACT; static final String JSON; static final String EMPTY_STRING; static final String JSON_NULL; static final String COMPACT_JSON_NULL; static final String COMPACT_JSON_EMPTY; }### Answer:
@Test public void shouldProperlyIndicateSupportedTypes() { assertThat(typeConverter.isApplicable(SUPPORTED_LIST_TYPE, null)).isTrue(); assertThat(typeConverter.isApplicable(SUPPORTED_MAP_TYPE, null)).isTrue(); assertThat(typeConverter.isApplicable(SUPPORTED_COMPLEX_TYPE, null)).isTrue(); assertThat(typeConverter.isApplicable(NOT_SUPPORTED_COMPLEX_TYPE, null)).isFalse(); } |
### Question:
ChainedTypeConverter implements TypeConverter<Object> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return converterFor(type, attributes, false) != null; } ChainedTypeConverter(List<TypeConverter<?>> converters); ChainedTypeConverter(TypeConverter<?>... converters); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Object fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Object value, Map<String, String> attributes); }### Answer:
@Test public void shouldSupportConvertersFromTheChain() { TypeConverter<?> converter = new ChainedTypeConverter(new StringConverter(false), new IntegerConverter()); assertThat(converter.isApplicable(String.class, null)).isTrue(); assertThat(converter.isApplicable(Integer.class, null)).isTrue(); assertThat(converter.isApplicable(Long.class, null)).isFalse(); } |
### Question:
ChainedTypeConverter implements TypeConverter<Object> { @Override public Object fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return converterFor(type, attributes).fromString(type, value, attributes); } ChainedTypeConverter(List<TypeConverter<?>> converters); ChainedTypeConverter(TypeConverter<?>... converters); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Object fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Object value, Map<String, String> attributes); }### Answer:
@Test public void shouldThrowIAEWhenTypeIsNotSupported() { assertThrows(IllegalArgumentException.class, () -> { TypeConverter<Object> converter = new ChainedTypeConverter(new StringConverter()); converter.fromString(Long.class, "10", null); }); } |
### Question:
FloatConverter extends AbstractNumberConverter<Float> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Float.class, Float.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableWhenFloatType() { Type type = Float.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotFloatType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
UrlConverter implements TypeConverter<URL> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && URL.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override URL fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, URL value, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableWhenUrlType() { Type type = URL.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotUrlType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
UrlConverter implements TypeConverter<URL> { @Override public String toString(Type type, URL value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return Objects.toString(value, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override URL fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, URL value, Map<String, String> attributes); }### Answer:
@Test public void shouldConvertToString() throws MalformedURLException { String urlString = "http: URL toConvert = new URL(urlString); String converted = converter.toString(URL.class, toConvert, emptyMap()); assertThat(converted).isEqualTo(urlString); }
@Test public void shouldReturnNullWhenConvertingToStringAndValueToConvertIsNull() { String converted = converter.toString(URL.class, null, emptyMap()); assertThat(converted).isNull(); } |
### Question:
UrlConverter implements TypeConverter<URL> { @Override public URL fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { return new URL(value); } catch (MalformedURLException e) { throw new IllegalArgumentException(format("Unable to convert to URL: %s", value), e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override URL fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, URL value, Map<String, String> attributes); }### Answer:
@Test public void shouldCovertFromString() throws MalformedURLException { String urlInString = "http: URL fromConversion = converter.fromString(URL.class, urlInString, emptyMap()); URL expected = new URL(urlInString); assertThat(fromConversion).isEqualTo(expected); }
@Test public void shouldThrowExceptionWhenMalformedUrl() { String malformedUrlString = "malformed URL"; assertThatThrownBy(() -> converter.fromString(URL.class, malformedUrlString, emptyMap())) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert to URL: malformed URL"); }
@Test public void shouldThrowExceptionWhenConvertingFromStringAndTypeIsNull() { String urlInString = "http: assertThatThrownBy(() -> converter.fromString(null, urlInString, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
@Test public void shouldReturnNullWhenConvertingFromStringAndValueToConvertIsNull() { URL fromConversion = converter.fromString(URL.class, null, emptyMap()); assertThat(fromConversion).isNull(); } |
### Question:
ShortConverter extends AbstractNumberConverter<Short> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Short.class, Short.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableWhenShortType() { Type type = Short.class; boolean applicable = shortTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); }
@Test public void shouldNotBeApplicableWhenNotShortType() { Type type = Boolean.class; boolean applicable = shortTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
@Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> shortTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
EnumConverter implements TypeConverter<Enum<?>> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Enum.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override Enum<?> fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Enum<?> value, Map<String, String> attributes); }### Answer:
@Test public void shouldAcceptEnumType() { Type type = TestEnum.class; boolean isApplicable = enumTypeAdapter.isApplicable(type, null); assertThat(isApplicable).isTrue(); } |
### Question:
EnumConverter implements TypeConverter<Enum<?>> { @SuppressWarnings("unchecked") @Override public Enum<?> fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : toEnumValue((Class<Enum<?>>) type, value); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override Enum<?> fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Enum<?> value, Map<String, String> attributes); }### Answer:
@Test public void shouldConvertFromString() { Enum<?> testEnum = enumTypeAdapter.fromString(TestEnum.class, "FIRST", null); assertThat(testEnum).isEqualTo(TestEnum.FIRST); }
@Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValue() { String value = "WRONG_VALUE"; assertThatThrownBy(() -> enumTypeAdapter.fromString(TestEnum.class, value, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert a value to an enumeration:"); } |
### Question:
YamlConverter implements TypeConverter<T> { @Override public String toString(Type type, T value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { ObjectWriter objectWriter = objectMapper.writer(); return objectWriter.writeValueAsString(value); } catch (JsonProcessingException e) { throw new UncheckedIOException("Unable to process JSON.", e); } } YamlConverter(); YamlConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer:
@Test void shouldConvertToString() { TestClass toConvert = new TestClass(1, "test-1"); String converted = typeConverter.toString(TestClass.class, toConvert, null); assertThat(converted).isEqualTo("" + "integer: 1\n" + "string: test-1\n"); }
@Test void shouldConvertCollectionToString() { List<TestClass> toConvert = asList( new TestClass(1, "test-1"), new TestClass(2, "test-2") ); TypeConverter<List<TestClass>> typeConverter = new YamlConverter<>(); String converted = typeConverter.toString(parameterize(Collection.class, TestClass.class), toConvert, null); assertThat(converted).isEqualTo("" + "- integer: 1\n" + " string: test-1\n" + "- integer: 2\n" + " string: test-2\n"); }
@Test void shouldConvertMapToString() { Map<String, TestClass> toConvert = new HashMap<>(); toConvert.put("first", new TestClass(1, "test-1")); toConvert.put("second", new TestClass(2, "test-2")); TypeConverter<Map<String, TestClass>> typeConverter = new YamlConverter<>(); String converted = typeConverter.toString(parameterize(Map.class, String.class, TestClass.class), toConvert, null); assertThat(converted).isEqualTo("" + "first:\n" + " integer: 1\n" + " string: test-1\n" + "second:\n" + " integer: 2\n" + " string: test-2\n"); }
@Test void shouldReturnNullWhenToStringAndValueIsNull() { String converted = typeConverter.toString(TestClass.class, null, null); assertThat(converted).isNull(); }
@Test void shouldThrowExceptionWhenTypeIsNullAndToString() { assertThatThrownBy(() -> typeConverter.toString(null, null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
EnumConverter implements TypeConverter<Enum<?>> { @Override public String toString(Type type, Enum<?> value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : value.name(); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override Enum<?> fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Enum<?> value, Map<String, String> attributes); }### Answer:
@Test public void shouldConvertToString() { String value = enumTypeAdapter.toString(TestEnum.class, TestEnum.SECOND_VALUE, null); assertThat(value).isEqualTo(TestEnum.SECOND_VALUE.name()); } |
### Question:
ConfigurationValueDecryptingProcessor implements ConfigurationValueProcessor { @Override public ConfigurationValue process(ConfigurationValue value) { requireNonNull(value, "value cannot be null"); if (value.isEncrypted() && Objects.equals(value.getEncryptionProvider(), decrypter.getName())) { String encrypted = value.getValue(); String decrypted = decrypter.decrypt(encrypted); value.setDecryptedValue(decrypted); } return value; } ConfigurationValueDecryptingProcessor(); ConfigurationValueDecryptingProcessor(ConfigurationValueDecrypter decrypter); void setDecrypter(ConfigurationValueDecrypter decrypter); @Override ConfigurationValue process(ConfigurationValue value); }### Answer:
@Test public void decryptUnencryptedValueAndResetProvider() { String encrypted = "encrypted"; String decrypted = "decrypted"; ConfigurationValue value = new ConfigurationValue(null, encrypted, true, Encrypted.DEFAULT, null); processor = new ConfigurationValueDecryptingProcessor(decrypter); when(decrypter.getName()).thenReturn(Encrypted.DEFAULT); when(decrypter.decrypt(encrypted)).thenReturn(decrypted); ConfigurationValue processed = processor.process(value); assertThat(processed).isSameAs(value); assertThat(value.isEncrypted()).isFalse(); assertThat(value.getValue()).isEqualTo(decrypted); verify(decrypter, times(1)).decrypt(anyString()); verify(decrypter, times(1)).getName(); }
@Test public void shouldNotDecryptUnencryptedValue() { String val = "value"; ConfigurationValue value = new ConfigurationValue(null, val, true, null, null); processor = new ConfigurationValueDecryptingProcessor(decrypter); processor.process(value); assertThat(value.isEncrypted()).isFalse(); assertThat(value.getValue()).isEqualTo(val); verify(decrypter, never()).getName(); verify(decrypter, never()).decrypt(anyString()); }
@Test public void shouldNotDecryptEncryptedValueWhenProviderNameDiffers() { String encrypted = "encrypted"; String decrypted = "decrypted"; String encryptionProvider = Encrypted.DEFAULT; ConfigurationValue value = new ConfigurationValue(null, encrypted, true, encryptionProvider, null); processor = new ConfigurationValueDecryptingProcessor(decrypter); when(decrypter.getName()).thenReturn("notMatchingProviderName"); when(decrypter.decrypt(encrypted)).thenReturn(decrypted); ConfigurationValue processed = processor.process(value); assertThat(processed).isSameAs(value); assertThat(value.isEncrypted()).isTrue(); assertThat(value.getEncryptionProvider()).isEqualTo(encryptionProvider); verify(decrypter, times(1)).getName(); verify(decrypter, never()).decrypt(anyString()); }
@Test public void shouldThrowIllegalArgumentExceptionFromNoOpConfigurationValueDecrypter() { assertThrows(IllegalArgumentException.class, () -> { processor = new ConfigurationValueDecryptingProcessor(); processor.process(new ConfigurationValue(null, null, true, Encrypted.DEFAULT, null)); }); } |
### Question:
JsonConverter implements TypeConverter<T> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); String converter = (attributes == null) ? null : attributes.get(CONVERTER); return ignoreConverterAttribute || Objects.equals(converter, JSON); } JsonConverter(); JsonConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer:
@Test void shouldThrowExceptionWhenTypeIsNullAndIsApplicable() { assertThatThrownBy(() -> typeConverter.isApplicable(null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
JsonConverter implements TypeConverter<T> { @Override public T fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { JavaType javaType = TypeFactory.defaultInstance().constructType(type); ObjectReader objectReader = objectMapper.readerFor(javaType); return objectReader.readValue(value); } catch (IOException e) { throw new IllegalStateException(e); } } JsonConverter(); JsonConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer:
@Test void shouldConvertFromString() { String toConvert = "" + "{" + " \"integer\": \"10\"," + " \"string\": \"test\"" + "}"; TestClass converted = typeConverter.fromString(TestClass.class, toConvert, null); assertThat(converted).isNotNull(); assertThat(converted.integer).isEqualTo(10); assertThat(converted.string).isEqualTo("test"); }
@Test void shouldConvertListFromString() { String toConvert = "" + "[" + " {" + " \"integer\": \"1\"," + " \"string\": \"test-1\"" + " }," + " {" + " \"integer\": \"2\"," + " \"string\": \"test-2\"" + " }" + "]"; TypeConverter<List<TestClass>> listConverter = new JsonConverter<>(); List<TestClass> converted = listConverter.fromString(parameterize(List.class, TestClass.class), toConvert, null); assertThat(converted) .hasSize(2) .containsSequence( new TestClass(1, "test-1"), new TestClass(2, "test-2")); }
@Test void shouldConvertMapFromString() { String toConvert = "" + "{" + " \"one\": {" + " \"integer\": \"1\"," + " \"string\": \"test-1\"" + " }," + " \"two\": {" + " \"integer\": \"2\"," + " \"string\": \"test-2\"" + " }" + "}"; TypeConverter<Map<String, TestClass>> listConverter = new JsonConverter<>(); Map<String, TestClass> converted = listConverter.fromString(parameterize(Map.class, String.class, TestClass.class), toConvert, null); assertThat(converted) .hasSize(2) .containsExactly( entry("one", new TestClass(1, "test-1")), entry("two", new TestClass(2, "test-2"))); }
@Test void shouldThrowAssertionErrorWhenTryToConvertFromStringWithInvalidProperty() { String toConvert = "" + "{" + " \"int\": \"10\"," + " \"string\": \"test\"" + "}"; assertThatThrownBy(() -> typeConverter.fromString(TestClass.class, toConvert, null)) .isExactlyInstanceOf(IllegalStateException.class) .hasCauseInstanceOf(IOException.class); }
@Test void shouldThrowAssertionErrorWhenTryToConvertFromInvalidJsonString() { String toConvert = "" + " \"integer\": \"10\"," + " \"string\": \"test\"" + "}"; assertThatThrownBy(() -> typeConverter.fromString(TestClass.class, toConvert, null)) .isExactlyInstanceOf(IllegalStateException.class) .hasCauseInstanceOf(IOException.class); }
@Test void shouldReturnNullWhenFromStringAndValueIsNull() { TestClass converted = typeConverter.fromString(TestClass.class, null, null); assertThat(converted).isNull(); }
@Test void shouldThrowExceptionWhenTypeIsNullAndFromString() { assertThatThrownBy(() -> typeConverter.fromString(null, null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
MetaDataExample { public static void main(String[] args) { new MetaDataExample().run(); } static void main(String[] args); }### Answer:
@Test public void shouldExecuteMainWithoutExceptions() { MetaDataExample.main(new String[0]); } |
### Question:
JsonConverter implements TypeConverter<T> { @Override public String toString(Type type, T value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { ObjectWriter objectWriter = objectMapper.writer(); return objectWriter.writeValueAsString(value); } catch (JsonProcessingException e) { throw new UncheckedIOException("Unable to process JSON.", e); } } JsonConverter(); JsonConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer:
@Test void shouldConvertToString() { TestClass toConvert = new TestClass(); toConvert.integer = 10; toConvert.string = "test"; String converted = typeConverter.toString(TestClass.class, toConvert, null); assertThat(converted).isEqualTo("" + "{" + "\"integer\":10," + "\"string\":\"test\"" + "}"); }
@Test void shouldReturnNullWhenToStringAndValueIsNull() { String converted = typeConverter.toString(TestClass.class, null, null); assertThat(converted).isNull(); }
@Test void shouldThrowExceptionWhenTypeIsNullAndToString() { assertThatThrownBy(() -> typeConverter.toString(null, null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } |
### Question:
KeySetUtils { public static List<String> keySet(KeyGenerator keyGenerator, List<String> keys, KeyGenerator fallbackKeyPrefixGenerator, String fallbackKey) { requireNonNull(keyGenerator, "keyGenerator cannot be null"); requireNonNull(keys, "keys cannot be null"); Set<String> keySet = new LinkedHashSet<>(keyGenerator.computeKeys(keys)); if (fallbackKeyPrefixGenerator != null) { keySet.addAll(fallbackKeyPrefixGenerator.computeKeys(keys)); } if (isNotBlank(fallbackKey)) { keySet.add(fallbackKey); } List<String> result = new ArrayList<>(keySet.size()); keySet.forEach(k -> result.add(k.intern())); return result; } private KeySetUtils(); static List<String> keySet(KeyGenerator keyGenerator, List<String> keys, KeyGenerator fallbackKeyPrefixGenerator, String fallbackKey); }### Answer:
@Test public void shouldCreateEmptyKeySet() { KeyGenerator keyGenerator = emptyKeyGenerator(); List<String> configurationKeys = emptyList(); KeyGenerator fallbackKeyPrefixGenerator = emptyKeyGenerator(); List<String> keys = KeySetUtils.keySet(keyGenerator, configurationKeys, fallbackKeyPrefixGenerator, null); assertThat(keys).isEmpty(); }
@Test public void shouldGenerateKeySet() { KeyGenerator keyGenerator = keyGenerator("fallback", "fallback.p1", "fallback.p1.p2"); List<String> configurationKeys = asList("key", "alternateKey", "duplicate", "duplicate"); KeyGenerator fallbackKeyPrefixGenerator = keyGenerator("fallbackKeyPrefix"); String fallbackKey = "fallbackKey"; List<String> keys = KeySetUtils.keySet(keyGenerator, configurationKeys, fallbackKeyPrefixGenerator, fallbackKey); assertThat(keys).containsSequence( "fallback.key", "fallback.alternateKey", "fallback.duplicate", "fallback.p1.key", "fallback.p1.alternateKey", "fallback.p1.duplicate", "fallback.p1.p2.key", "fallback.p1.p2.alternateKey", "fallback.p1.p2.duplicate", "fallbackKeyPrefix.key", "fallbackKeyPrefix.alternateKey", "fallbackKeyPrefix.duplicate", "fallbackKey" ); } |
### Question:
SpringAnnotationBasedExample { public static void main(String[] args) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringAnnotationBasedExample.class)) { context.getBean(SpringAnnotationBasedExample.class).run(); } } static void main(String[] args); }### Answer:
@Test public void shouldExecuteMainWithoutExceptions() { SpringAnnotationBasedExample.main(new String[0]); } |
### Question:
AnnotationMetadataExtractor implements MetadataExtractor { @Override public List<String> getPrefixes(Class<?> configurationType) { Key keyAnnotation = findAnnotation(configurationType, Key.class); String[] prefixes = (keyAnnotation == null) ? null : keyAnnotation.value(); if (prefixes != null && prefixes.length == 0) { prefixes = new String[]{decapitalize(configurationType.getSimpleName())}; } return prefixes == null ? emptyList() : unmodifiableList(asList(prefixes)); } static MetadataExtractor getInstance(); @Override boolean isConfigurationClass(Class<?> clazz); @Override boolean isAbstractConfiguration(Class<?> clazz); @Override boolean isValueConfigurationMethod(Class<?> configurationType, Method method); @Override boolean isSubConfigurationMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationType(Class<?> configurationType, Method method); @Override boolean isSubConfigurationListMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationListElementType(Class<?> configurationType, Method method); @Override String getDescription(Class<?> configurationType); @Override String getDescription(Class<?> configurationType, Method method); @Override List<String> getKeys(Class<?> configurationType, Method method); @Override List<String> getPrefixes(Class<?> configurationType); @Override List<String> getPrefixes(Class<?> configurationType, Method method); @Override boolean shouldResetPrefix(Class<?> configurationType, Method method); @Override String getFallbackKey(Class<?> configurationType, Method method); @Override @SuppressWarnings("unchecked") Class<TypeConverter<?>> getTypeConverter(Class<?> configurationType, Method method); @Override String getEncryptionProvider(Class<?> configurationType, Method method); @Override Integer getDefaultSubConfigurationListSize(Class<?> configurationType, Method method); @Override OptionalValue<String> getDefaultValue(Class<?> configurationType, Method method); @Override Map<String, String> getSubConfigurationDefaultValues(Class<?> configurationType, Method method); @Override List<Map<String, String>> getSubConfigurationListDefaultValues(Class<?> configurationType, Method method); @Override Map<String, String> attributes(Class<?> configurationType); @Override Map<String, String> attributes(Class<?> configurationType, Method method); }### Answer:
@Test public void shouldProvidePrefixForSubConfiguration() { List<String> prefixes = extractor.getPrefixes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfiguration")); assertThat(prefixes).containsSequence("subConfiguration"); prefixes = extractor.getPrefixes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfigurations")); assertThat(prefixes).containsSequence("subConfigurations"); }
@Test public void shouldProvidePrefixForSubConfigurationWithPrefix() { List<String> prefixes = extractor.getPrefixes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfigurationWithPrefix")); assertThat(prefixes).isEmpty(); prefixes = extractor.getPrefixes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfigurationWithPrefixList")); assertThat(prefixes).isEmpty(); } |
### Question:
AnnotationMetadataExtractor implements MetadataExtractor { @Override public List<Map<String, String>> getSubConfigurationListDefaultValues(Class<?> configurationType, Method method) { Class<?> subConfigurationClazz = getSubConfigurationListElementType(configurationType, method); Annotation[] defaultsAnnotations = getDefaultsAnnotations(subConfigurationClazz, method); return getDefaultValues(defaultsAnnotations); } static MetadataExtractor getInstance(); @Override boolean isConfigurationClass(Class<?> clazz); @Override boolean isAbstractConfiguration(Class<?> clazz); @Override boolean isValueConfigurationMethod(Class<?> configurationType, Method method); @Override boolean isSubConfigurationMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationType(Class<?> configurationType, Method method); @Override boolean isSubConfigurationListMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationListElementType(Class<?> configurationType, Method method); @Override String getDescription(Class<?> configurationType); @Override String getDescription(Class<?> configurationType, Method method); @Override List<String> getKeys(Class<?> configurationType, Method method); @Override List<String> getPrefixes(Class<?> configurationType); @Override List<String> getPrefixes(Class<?> configurationType, Method method); @Override boolean shouldResetPrefix(Class<?> configurationType, Method method); @Override String getFallbackKey(Class<?> configurationType, Method method); @Override @SuppressWarnings("unchecked") Class<TypeConverter<?>> getTypeConverter(Class<?> configurationType, Method method); @Override String getEncryptionProvider(Class<?> configurationType, Method method); @Override Integer getDefaultSubConfigurationListSize(Class<?> configurationType, Method method); @Override OptionalValue<String> getDefaultValue(Class<?> configurationType, Method method); @Override Map<String, String> getSubConfigurationDefaultValues(Class<?> configurationType, Method method); @Override List<Map<String, String>> getSubConfigurationListDefaultValues(Class<?> configurationType, Method method); @Override Map<String, String> attributes(Class<?> configurationType); @Override Map<String, String> attributes(Class<?> configurationType, Method method); }### Answer:
@Test public void shouldProvideDefaultValuesForSubConfigurationList() { List<Map<String, String>> values = extractor.getSubConfigurationListDefaultValues(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfigurations")); assertThat(values).hasSize(2); assertThat(values.get(0)).contains( entry("one", "1"), entry("two", "first")); assertThat(values.get(1)).contains( entry("one", "2"), entry("two", "second")); } |
### Question:
AnnotationMetadataExtractor implements MetadataExtractor { @Override public Map<String, String> getSubConfigurationDefaultValues(Class<?> configurationType, Method method) { if (!isAnnotationDeclaredLocally(method.getReturnType(), DefaultsAnnotation.class)) { return emptyMap(); } Class<?> defaultsAnnotation = findAnnotation(method.getReturnType(), DefaultsAnnotation.class).value(); @SuppressWarnings("unchecked") Annotation annotation = findAnnotation(method, (Class<? extends Annotation>) defaultsAnnotation); return getDefaultValues(annotation); } static MetadataExtractor getInstance(); @Override boolean isConfigurationClass(Class<?> clazz); @Override boolean isAbstractConfiguration(Class<?> clazz); @Override boolean isValueConfigurationMethod(Class<?> configurationType, Method method); @Override boolean isSubConfigurationMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationType(Class<?> configurationType, Method method); @Override boolean isSubConfigurationListMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationListElementType(Class<?> configurationType, Method method); @Override String getDescription(Class<?> configurationType); @Override String getDescription(Class<?> configurationType, Method method); @Override List<String> getKeys(Class<?> configurationType, Method method); @Override List<String> getPrefixes(Class<?> configurationType); @Override List<String> getPrefixes(Class<?> configurationType, Method method); @Override boolean shouldResetPrefix(Class<?> configurationType, Method method); @Override String getFallbackKey(Class<?> configurationType, Method method); @Override @SuppressWarnings("unchecked") Class<TypeConverter<?>> getTypeConverter(Class<?> configurationType, Method method); @Override String getEncryptionProvider(Class<?> configurationType, Method method); @Override Integer getDefaultSubConfigurationListSize(Class<?> configurationType, Method method); @Override OptionalValue<String> getDefaultValue(Class<?> configurationType, Method method); @Override Map<String, String> getSubConfigurationDefaultValues(Class<?> configurationType, Method method); @Override List<Map<String, String>> getSubConfigurationListDefaultValues(Class<?> configurationType, Method method); @Override Map<String, String> attributes(Class<?> configurationType); @Override Map<String, String> attributes(Class<?> configurationType, Method method); }### Answer:
@Test public void shouldProvideDefaultValuesForSubConfiguration() { Map<String, String> values = extractor.getSubConfigurationDefaultValues(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfiguration")); assertThat(values).hasSize(2); assertThat(values).contains( entry("one", "1"), entry("two", "the one")); } |
### Question:
AnnotationMetadataExtractor implements MetadataExtractor { @Override public Map<String, String> attributes(Class<?> configurationType) { return AttributesUtils.attributes(getMetaAttributes(configurationType)); } static MetadataExtractor getInstance(); @Override boolean isConfigurationClass(Class<?> clazz); @Override boolean isAbstractConfiguration(Class<?> clazz); @Override boolean isValueConfigurationMethod(Class<?> configurationType, Method method); @Override boolean isSubConfigurationMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationType(Class<?> configurationType, Method method); @Override boolean isSubConfigurationListMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationListElementType(Class<?> configurationType, Method method); @Override String getDescription(Class<?> configurationType); @Override String getDescription(Class<?> configurationType, Method method); @Override List<String> getKeys(Class<?> configurationType, Method method); @Override List<String> getPrefixes(Class<?> configurationType); @Override List<String> getPrefixes(Class<?> configurationType, Method method); @Override boolean shouldResetPrefix(Class<?> configurationType, Method method); @Override String getFallbackKey(Class<?> configurationType, Method method); @Override @SuppressWarnings("unchecked") Class<TypeConverter<?>> getTypeConverter(Class<?> configurationType, Method method); @Override String getEncryptionProvider(Class<?> configurationType, Method method); @Override Integer getDefaultSubConfigurationListSize(Class<?> configurationType, Method method); @Override OptionalValue<String> getDefaultValue(Class<?> configurationType, Method method); @Override Map<String, String> getSubConfigurationDefaultValues(Class<?> configurationType, Method method); @Override List<Map<String, String>> getSubConfigurationListDefaultValues(Class<?> configurationType, Method method); @Override Map<String, String> attributes(Class<?> configurationType); @Override Map<String, String> attributes(Class<?> configurationType, Method method); }### Answer:
@Test public void shouldProvideAttributesForValueProperty() { Map<String, String> attributes = extractor.attributes(TestConfiguration.class, getMethod(TestConfiguration.class, "getUrl")); assertThat(attributes).containsExactly( entry("custom", "url")); }
@Test public void shouldProvideAttributesForSubConfigurationProperty() { Map<String, String> attributes = extractor.attributes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfiguration")); assertThat(attributes).containsExactly( entry("custom", "sub-configuration")); }
@Test public void shouldProvideAttributesForSubConfigurationListProperty() { Map<String, String> attributes = extractor.attributes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfigurations")); assertThat(attributes).containsExactly( entry("custom", "sub-configuration-list")); }
@Test public void shouldProvideAttributesForType() { Map<String, String> attributes = extractor.attributes(TestConfiguration.class); assertThat(attributes).containsExactly( entry("type1", "value1"), entry("type2", "value2")); }
@Test public void shouldProvideAttributesForCustomMetaAnnotations() { Map<String, String> attributes = extractor.attributes(TestConfiguration.class, getMethod(TestConfiguration.class, "getCustomMetaAnnotations")); assertThat(attributes).containsOnly( entry("fixed-one", "one"), entry("fixed-two", "two"), entry("custom", "custom-meta"), entry("attribute", "custom-attribute"), entry("another-attribute", "another-custom-attribute") ); } |
### Question:
SpringExample { public static void main(String[] args) { new SpringExample().run(); } static void main(String[] args); }### Answer:
@Test public void shouldExecuteMainWithoutExceptions() { SpringExample.main(new String[0]); } |
### Question:
CoreExample { public static void main(String[] args) { new CoreExample().run(); } static void main(String[] args); }### Answer:
@Test public void shouldExecuteMainWithoutExceptions() { CoreExample.main(new String[0]); } |
### Question:
MethodsProvider { public Collection<Method> getAllDeclaredMethods(Class<?> configurationType) { Class<?> type = configurationType; Set<MethodWrapper> methods = new LinkedHashSet<>(addMethods(type.getMethods())); if (type.getSuperclass() != null) { do { methods.addAll(addMethods(type.getDeclaredMethods())); type = type.getSuperclass(); } while (!Object.class.equals(type)); } return methods.stream() .map(MethodWrapper::getMethod) .collect(toList()); } Collection<Method> getAllDeclaredMethods(Class<?> configurationType); }### Answer:
@Test public void shouldFindPublicAbstractMethodInClass() throws NoSuchMethodException { abstract class TestClass { public abstract int propertyA(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(TestClass.class.getMethod("propertyA")); }
@Test public void shouldFindPublicAbstractMethodInheritedFromAbstractMethod() throws NoSuchMethodException { abstract class AbstractClass { public abstract int propertyA(); } abstract class TestClass extends AbstractClass { public abstract int propertyB(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(AbstractClass.class.getMethod("propertyA"), TestClass.class.getMethod("propertyB")); }
@Test public void shouldFindMethodInheritedFromInterface() throws NoSuchMethodException { abstract class TestClass implements TestInterface { public abstract int propertyB(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(TestInterface.class.getMethod("propertyA"), TestClass.class.getMethod("propertyB")); }
@Test public void shouldHandleMethodFromSubclass() throws NoSuchMethodException { abstract class BaseConf { public abstract Integer propertyA(); } abstract class SpecificConf extends BaseConf { @Override public abstract Integer propertyA(); } abstract class AbstractClass { public abstract BaseConf propertyB(); } abstract class TestClass extends AbstractClass { @Override public abstract SpecificConf propertyB(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(TestClass.class.getMethod("propertyB")); } |
### Question:
PropertySourceConfigurationSource implements ConfigurationSource, BeanFactoryAware, EnvironmentAware, InitializingBean { @Override public OptionalValue<String> getValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); for (PropertySource<?> propertySource : flattenedPropertySources) { OptionalValue<String> value = getProperty(propertySource, key); if (value.isPresent()) { return value; } } return absent(); } void setPropertySources(PropertySources propertySources); @Override void setBeanFactory(BeanFactory beanFactory); @Override void setEnvironment(Environment environment); void setConversionService(ConversionService conversionService); @Override void afterPropertiesSet(); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes); }### Answer:
@Test public void shouldResolvePropertyPlaceholdersSetWithCorrectOrder() { assertThat(source.getValue("property.only.in.A", null)).isEqualTo(present("A")); assertThat(source.getValue("property.only.in.B", null)).isEqualTo(present("B")); assertThat(source.getValue("property.in.A.and.B", null)).isEqualTo(present("B")); } |
### Question:
AttributesUtils implements Serializable { public static Map<String, String> attributes(Map<String, String> attributes) { return getCached(attributes, true); } private AttributesUtils(); static Map<String, String> attributes(Map<String, String> attributes); static Map<String, String> mergeAttributes(Map<String, String> parent, Map<String, String> child); }### Answer:
@Test public void shouldReturnNullWhenPropertiesAreNull() { Map<String, String> properties = null; Map<String, String> attributes = attributes(properties); assertThat(attributes).isNull(); }
@Test public void shouldConstructFromMap() { Map<String, String> properties = MapUtils.of("key1", "val1", "key2", "val2"); Map<String, String> attributes = attributes(properties); assertThat(attributes).isNotNull(); assertThat(attributes).contains(entry("key1", "val1"), entry("key2", "val2")); }
@Test public void shouldBeImmutable() { assertThrows(UnsupportedOperationException.class, () -> attributes(MapUtils.of("key", "value")).put("anything", "value") ); }
@Test public void shouldProvideSameInstanceForSameProperties() { Map<String, String> properties = MapUtils.of("key1", "value1", "key2", "value2"); Map<String, String> sameProperties = new HashMap<>(properties); Map<String, String> attributes = attributes(properties); Map<String, String> attributesForSameProperties = attributes(sameProperties); assertThat(attributesForSameProperties).isSameAs(attributes); } |
### Question:
AttributesUtils implements Serializable { public static Map<String, String> mergeAttributes(Map<String, String> parent, Map<String, String> child) { if (parent == null) { return getCached(child, true); } if (child == null) { return getCached(parent, true); } Map<String, String> merged = new LinkedHashMap<>(parent.size() + child.size()); merged.putAll(parent); merged.putAll(child); return getCached(unmodifiableMap(merged), false); } private AttributesUtils(); static Map<String, String> attributes(Map<String, String> attributes); static Map<String, String> mergeAttributes(Map<String, String> parent, Map<String, String> child); }### Answer:
@Test public void shouldMergeToNullWhenBothAreNull() { Map<String, String> merged = mergeAttributes(null, null); assertThat(merged).isNull(); } |
### Question:
CachingTypeConverter implements TypeConverter<T>, InitializingBean { @SuppressWarnings("unchecked") @Override public T fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); SimpleKey key = new SimpleKey(type, attributes, value); ValueWrapper valueWrapper = cache.get(key); if (valueWrapper != null) { return (T) valueWrapper.get(); } else { T val = typeConverter.fromString(type, value, attributes); valueWrapper = cache.putIfAbsent(key, val); if (valueWrapper == null) { return val; } else { return (T) valueWrapper.get(); } } } TypeConverter<?> getTypeConverter(); void setTypeConverter(TypeConverter<T> typeConverter); CacheManager getCacheManager(); void setCacheManager(CacheManager cacheManager); String getCacheName(); void setCacheName(String cacheName); @Override void afterPropertiesSet(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer:
@Test public void shouldIntegrateWithSpring() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class)) { TypeConverter<?> typeConverter = context.getBean(TypeConverter.class); assertThat(typeConverter).isInstanceOf(CachingTypeConverter.class); Long val = (Long) typeConverter.fromString(Long.class, "10", null); Long val2 = (Long) typeConverter.fromString(Long.class, "10", null); assertThat(val).isEqualTo(10L); assertThat(val2).isSameAs(val); SampleConfiguration configuration = context.getBean(SampleConfiguration.class); Long valueFromConfiguration = configuration.getValue(); assertThat(valueFromConfiguration).isEqualTo(10L); assertThat(valueFromConfiguration).isSameAs(val); } } |
### Question:
PropertyUtils { public static Object getProperty(Object bean, String name) { requireNonNull(bean, "bean cannot be null"); requireNonNull(name, "name cannot be null"); Class<?> beanClass = bean.getClass(); try { PropertyDescriptor descriptor = findPropertyDescriptor(beanClass, name); Method readMethod = descriptor.getReadMethod(); return readMethod.invoke(bean, EMPTY_OBJECT_ARRAY); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Unable to get property " + name + " on " + bean.getClass(), e); } } private PropertyUtils(); static String getPropertyName(Method method); static Object getProperty(Object bean, String name); static void setProperty(Object bean, String name, Object value); }### Answer:
@Test public void shouldGetProperties() { Bean bean = new Bean(); assertThat(getProperty(bean, "intValue")).isEqualTo(0); assertThat(getProperty(bean, "stringValue")).isNull(); assertThat(getProperty(bean, "beanValue")).isNull(); bean.setIntValue(1); assertThat(getProperty(bean, "intValue")).isEqualTo(bean.getIntValue()); bean.setStringValue("string"); assertThat(getProperty(bean, "stringValue")).isSameAs(bean.getStringValue()); bean.setBeanValue(new Bean()); assertThat(getProperty(bean, "beanValue")).isSameAs(bean.getBeanValue()); }
@Test public void getPropertyShouldThrowNoSuchMethodExceptionWhenPropertyNotFound() { assertThrows(IllegalArgumentException.class, () -> getProperty(new Bean(), "unknownProperty")); }
@Test public void getPropertyShouldThrowNoSuchMethodExceptionWhenPropertyIsCapitalized() { assertThrows(IllegalArgumentException.class, () -> getProperty(new Bean(), "BeanValue")); }
@Test public void getPropertyShouldThrowNullPointerExceptionWhenNullBean() { assertThrows(NullPointerException.class, () -> getProperty(null, "intValue")); }
@Test public void getPropertyShouldThrowNullPointerExceptionWhenNullPropertyName() { assertThrows(NullPointerException.class, () -> getProperty(new Bean(), null)); } |
### Question:
PropertyUtils { public static void setProperty(Object bean, String name, Object value) { requireNonNull(bean, "bean cannot be null"); requireNonNull(name, "name cannot be null"); Class<?> beanClass = bean.getClass(); try { PropertyDescriptor descriptor = findPropertyDescriptor(beanClass, name); Method writeMethod = descriptor.getWriteMethod(); if (writeMethod == null) { throw new IllegalArgumentException("Unable to set property '" + name + " on " + bean.getClass() + " because setter of type " + descriptor.getPropertyType() + " is not available"); } writeMethod.invoke(bean, value); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Unable to set property " + name + " on " + bean.getClass(), e); } } private PropertyUtils(); static String getPropertyName(Method method); static Object getProperty(Object bean, String name); static void setProperty(Object bean, String name, Object value); }### Answer:
@Test public void shouldSetProperties() { Bean bean = new Bean(); setProperty(bean, "intValue", 1); assertThat(bean.getIntValue()).isEqualTo(1); setProperty(bean, "stringValue", "string"); assertThat(bean.getStringValue()).isEqualTo("string"); Bean beanValue = new Bean(); setProperty(bean, "beanValue", beanValue); assertThat(bean.getBeanValue()).isSameAs(beanValue); setProperty(bean, "stringValue", null); assertThat(bean.getStringValue()).isNull(); }
@Test public void setPropertyShouldThrowExceptionWhenPropertyTypeMismatch() { assertThrows(IllegalArgumentException.class, () -> setProperty(new Bean(), "beanValue", "invalid-type")); }
@Test public void setPropertyShouldThrowNoSuchMethodExceptionWhenPropertyNotFound() { assertThrows(IllegalArgumentException.class, () -> setProperty(new Bean(), "unknownProperty", null)); }
@Test public void setPropertyShouldThrowNoSuchMethodExceptionWhenPropertyIsCapitalized() { assertThrows(IllegalArgumentException.class, () -> setProperty(new Bean(), "BeanValue", null)); }
@Test public void setPropertyShouldThrowNullPointerExceptionWhenNullBean() { assertThrows(NullPointerException.class, () -> setProperty(null, "intValue", 1)); }
@Test public void setPropertyShouldThrowNullPointerExceptionWhenNullPropertyName() { assertThrows(NullPointerException.class, () -> setProperty(new Bean(), null, null)); } |
### Question:
JaxbConverter implements TypeConverter<T> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class && ((AnnotatedElement) type).getAnnotation(XmlRootElement.class) != null; } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer:
@Test public void shouldBeApplicableForMultipleXmlTypes() { assertThat(jaxbTypeConverter.isApplicable(XmlRootConfiguration01.class, null)).isTrue(); assertThat(jaxbTypeConverter.isApplicable(XmlRootConfiguration02.class, null)).isTrue(); }
@Test public void shouldNotBeApplicableForNonXmlTypes() { assertThat(jaxbTypeConverter.isApplicable(NonXmlConfiguration.class, null)).isFalse(); } |
### Question:
PropertyUtils { public static String getPropertyName(Method method) { requireNonNull(method, "method cannot be null"); String name = method.getName(); if (name.startsWith("set")) { if (method.getParameterCount() != 1) { throw new IllegalArgumentException("Method " + method + " is not a valid setter."); } name = name.substring(3); } else if (name.startsWith("get") || name.startsWith("is")) { if (method.getParameterCount() != 0 || void.class.equals(method.getReturnType())) { throw new IllegalArgumentException("Method " + method + " is not a valid getter."); } name = name.substring(name.startsWith("get") ? 3 : 2); } else { throw new IllegalArgumentException("Method " + name + " is not a valid getter nor setter."); } return decapitalize(name); } private PropertyUtils(); static String getPropertyName(Method method); static Object getProperty(Object bean, String name); static void setProperty(Object bean, String name, Object value); }### Answer:
@Test public void getPropertyNameShouldProvidePropertyNameFromValidAccessor() { assertThat(getPropertyName(getMethod(Bean.class, "getIntValue"))).isEqualTo("intValue"); assertThat(getPropertyName(getMethod(Bean.class, "setIntValue"))).isEqualTo("intValue"); assertThat(getPropertyName(getMethod(Bean.class, "getStringValue"))).isEqualTo("stringValue"); assertThat(getPropertyName(getMethod(Bean.class, "isBooleanValue"))).isEqualTo("booleanValue"); assertThat(getPropertyName(getMethod(Bean.class, "setBooleanValue"))).isEqualTo("booleanValue"); }
@Test public void getPropertyNameShouldThrowNPEWhenMethodIsNull() { assertThrows(NullPointerException.class, () -> getPropertyName(null)); }
@Test public void getPropertyNameShouldThrowIAEWhenMethodIsNotGetterNorSetter() { assertThrows(IllegalArgumentException.class, () -> getPropertyName(getMethod(Bean.class, "equals"))); } |
### Question:
MultiConfigurationSource implements ConfigurationSource { @Override public OptionalValue<String> getValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); for (ConfigurationSource source : sources) { OptionalValue<String> value = source.getValue(key, attributes); if (value.isPresent()) { return value; } } return absent(); } MultiConfigurationSource(List<ConfigurationSource> sources); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes); }### Answer:
@Test public void shouldReturnValuesFromProperSource() { assertThat(source.getValue(A_KEY, null).get()).isEqualTo(A_KEY); assertThat(source.getValue(B_KEY, null).get()).isEqualTo(B_KEY); } |
### Question:
MultiConfigurationSource implements ConfigurationSource { @Override public ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes) { requireNonNull(keys, "keys cannot be null"); for (ConfigurationSource source : sources) { ConfigurationEntry entry = source.findEntry(keys, attributes); if (entry != null) { return entry; } } return null; } MultiConfigurationSource(List<ConfigurationSource> sources); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes); }### Answer:
@Test public void shouldFindValuesInProperSource() { assertThat(source.findEntry(asList("NotExistingKey", B_KEY), null)).isEqualTo(new ConfigurationEntry(B_KEY, B_KEY)); } |
### Question:
MapConfigurationSource implements IterableConfigurationSource { @Override public OptionalValue<String> getValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); String value = source.get(key); return value != null || source.containsKey(key) ? present(value) : absent(); } MapConfigurationSource(Map<String, String> source); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override Iterable<ConfigurationEntry> getAllConfigurationEntries(); }### Answer:
@Test public void shouldGetSingleValueFromUnderlyingMap() { ConfigurationSource source = new MapConfigurationSource(of("key1", "value1", "key2", "value2")); String value = source.getValue("key2", null).get(); assertThat(value).isEqualTo("value2"); } |
### Question:
MapConfigurationSource implements IterableConfigurationSource { @Override public Iterable<ConfigurationEntry> getAllConfigurationEntries() { return new MapConfigurationEntryIterable(source); } MapConfigurationSource(Map<String, String> source); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override Iterable<ConfigurationEntry> getAllConfigurationEntries(); }### Answer:
@Test public void shouldIterateOver() { MapConfigurationSource source = new MapConfigurationSource(of("key1", "value1", "key2", "value2")); Iterable<ConfigurationEntry> iterable = source.getAllConfigurationEntries(); assertThat(iterable).containsExactly(new ConfigurationEntry("key1", "value1"), new ConfigurationEntry("key2", "value2")); } |
### Question:
WritableMapConfigurationSource extends MapConfigurationSource implements WritableConfigurationSource { @Override public void setValue(String key, String value, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); source.put(key, value); } WritableMapConfigurationSource(Map<String, String> source); @Override void setValue(String key, String value, Map<String, String> attributes); @Override OptionalValue<String> removeValue(String key, Map<String, String> attributes); }### Answer:
@Test public void shouldSetAndGetValue() { WritableConfigurationSource mapConfigurationSource = new WritableMapConfigurationSource(new HashMap<>()); mapConfigurationSource.setValue("key", "value", null); OptionalValue<String> value = mapConfigurationSource.getValue("key", null); assertThat(value.isPresent()).isTrue(); assertThat(value.get()).isEqualTo("value"); } |
### Question:
MatchingChangeoverNormsDetailsListeners { public void matchingChangeoverNorm(final ViewDefinitionState viewDefinitionState, final ComponentState state, final String[] args) { Entity fromTechnology = ((LookupComponent) viewDefinitionState.getComponentByReference(MATCHING_FROM_TECHNOLOGY)) .getEntity(); Entity toTechnology = ((LookupComponent) viewDefinitionState.getComponentByReference(MATCHING_TO_TECHNOLOGY)).getEntity(); Entity productionLine = ((LookupComponent) viewDefinitionState.getComponentByReference(MATCHING_PRODUCTION_LINE)) .getEntity(); FormComponent form = (FormComponent) viewDefinitionState.getComponentByReference("form"); Entity changeoverNorm = changeoverNormsService.getMatchingChangeoverNorms(fromTechnology, toTechnology, productionLine); if (changeoverNorm == null) { clearField(viewDefinitionState); changeStateEditButton(viewDefinitionState, false); form.setFieldValue(null); } else { form.setFieldValue(changeoverNorm.getId()); fillField(viewDefinitionState, changeoverNorm); changeStateEditButton(viewDefinitionState, true); } } void matchingChangeoverNorm(final ViewDefinitionState viewDefinitionState, final ComponentState state,
final String[] args); void redirectToChangedNormsDetails(final ViewDefinitionState viewDefinitionState, final ComponentState state,
final String[] args); void enabledButtonAfterSelectionTechnologies(final ViewDefinitionState viewDefinitionState,
final ComponentState state, final String[] args); void changeStateEditButton(final ViewDefinitionState view, final boolean enabled); void clearField(final ViewDefinitionState view); void fillField(final ViewDefinitionState view, final Entity entity); }### Answer:
@Test public void shouldClearFieldAndDisabledButtonWhenMatchingChangeoverNormWasnotFound() throws Exception { when(changeoverNormsService.getMatchingChangeoverNorms(fromTechnology, toTechnology, productionLine)).thenReturn(null); when(view.getComponentByReference(NUMBER)).thenReturn(number); when(view.getComponentByReference(FROM_TECHNOLOGY)).thenReturn(fromTechLookup); when(view.getComponentByReference(TO_TECHNOLOGY)).thenReturn(toTechLookup); when(view.getComponentByReference(FROM_TECHNOLOGY_GROUP)).thenReturn(fromTechGpLookup); when(view.getComponentByReference(TO_TECHNOLOGY_GROUP)).thenReturn(toTechGpLookup); when(view.getComponentByReference(CHANGEOVER_TYPE)).thenReturn(changeoverTypField); when(view.getComponentByReference(DURATION)).thenReturn(durationField); when(view.getComponentByReference(PRODUCTION_LINE)).thenReturn(productionLineLookup); when(view.getComponentByReference("form")).thenReturn(form); when(view.getComponentByReference("window")).thenReturn((ComponentState) window); when(window.getRibbon()).thenReturn(ribbon); when(ribbon.getGroupByName("matching")).thenReturn(matching); when(ribbon.getGroupByName("editing")).thenReturn(matching); when(matching.getItemByName("edit")).thenReturn(edit); listeners.matchingChangeoverNorm(view, state, null); Mockito.verify(fromTechLookup).setFieldValue(null); Mockito.verify(edit).setEnabled(false); } |
### Question:
ProductionTrackingDetailsHooks { public void initializeProductionTrackingDetailsView(final ViewDefinitionState view) { FormComponent productionTrackingForm = (FormComponent) view.getComponentByReference(L_FORM); FieldComponent stateField = (FieldComponent) view.getComponentByReference(ProductionTrackingFields.STATE); LookupComponent orderLookup = (LookupComponent) view.getComponentByReference(ProductionTrackingFields.ORDER); FieldComponent isDisabledField = (FieldComponent) view.getComponentByReference(L_IS_DISABLED); Entity productionTracking = productionTrackingForm.getEntity(); stateField.setFieldValue(productionTracking.getField(ProductionTrackingFields.STATE)); stateField.requestComponentUpdateState(); Entity order = orderLookup.getEntity(); isDisabledField.setFieldValue(false); if (order != null) { productionTrackingService.setTimeAndPieceworkComponentsVisible(view, order); } } void onBeforeRender(final ViewDefinitionState view); void setCriteriaModifierParameters(final ViewDefinitionState view); void initializeProductionTrackingDetailsView(final ViewDefinitionState view); void changeFieldComponentsEnabledAndGridsEditable(final ViewDefinitionState view); void updateRibbonState(final ViewDefinitionState view); }### Answer:
@Test public void shouldSetStateToDraftWhenInitializeTrackingDetailsViewIfProductionTrackingIsntSaved() { given(productionTrackingForm.getEntityId()).willReturn(null); given(productionTrackingForm.getEntity()).willReturn(productionTracking); given(productionTracking.getField(ProductionTrackingFields.STATE)).willReturn(ProductionTrackingStateStringValues.DRAFT); productionTrackingDetailsHooks.initializeProductionTrackingDetailsView(view); verify(stateField, times(1)).setFieldValue(ProductionTrackingStateStringValues.DRAFT); verify(isDisabledField, times(1)).setFieldValue(false); verify(productionTrackingService, never()).setTimeAndPieceworkComponentsVisible(view, order); }
@Test public void shouldSetStateToAcceptedWhenInitializeTrackingDetailsViewIfProductionTrackingIsSaved() { given(productionTrackingForm.getEntityId()).willReturn(1L); given(productionTrackingForm.getEntity()).willReturn(productionTracking); given(productionTracking.getField(ProductionTrackingFields.STATE)).willReturn( ProductionTrackingStateStringValues.ACCEPTED); given(orderLookup.getEntity()).willReturn(order); productionTrackingDetailsHooks.initializeProductionTrackingDetailsView(view); verify(stateField, times(1)).setFieldValue(ProductionTrackingStateStringValues.ACCEPTED); verify(isDisabledField, times(1)).setFieldValue(false); verify(productionTrackingService, times(1)).setTimeAndPieceworkComponentsVisible(view, order); } |
### Question:
AvgLaborCostCalcForOrderDetailsHooks { public void enabledButtonForCopyNorms(final ViewDefinitionState view) { WindowComponent window = (WindowComponent) view.getComponentByReference("window"); RibbonActionItem copyToOperationsNorms = window.getRibbon().getGroupByName("hourlyCostNorms") .getItemByName("copyToOperationsNorms"); FieldComponent averageLaborHourlyCost = (FieldComponent) view.getComponentByReference(AVERAGE_LABOR_HOURLY_COST); if (StringUtils.isEmpty((String) averageLaborHourlyCost.getFieldValue())) { copyToOperationsNorms.setEnabled(false); } else { copyToOperationsNorms.setEnabled(true); } copyToOperationsNorms.requestUpdate(true); } void enabledButtonForCopyNorms(final ViewDefinitionState view); }### Answer:
@Test public void shouldEnabledButtonForCopyNorms() throws Exception { String averageLaborHourlyCostValue = "50"; when(averageLaborHourlyCost.getFieldValue()).thenReturn(averageLaborHourlyCostValue); orderDetailsHooks.enabledButtonForCopyNorms(view); Mockito.verify(copyToOperationsNorms).setEnabled(true); }
@Test public void shouldDisbaleButtonForCopyNorms() throws Exception { String averageLaborHourlyCostValue = ""; when(averageLaborHourlyCost.getFieldValue()).thenReturn(averageLaborHourlyCostValue); orderDetailsHooks.enabledButtonForCopyNorms(view); Mockito.verify(copyToOperationsNorms).setEnabled(false); } |
### Question:
GenerateProductionBalanceWithCosts implements Observer { public void doTheCostsPart(final Entity productionBalance) { Entity order = productionBalance.getBelongsToField(ProductionBalanceFields.ORDER); Entity technology = order.getBelongsToField(OrderFields.TECHNOLOGY); Entity productionLine = order.getBelongsToField(OrderFields.PRODUCTION_LINE); productionBalance.setField(ProductionBalanceFields.ORDER, order); BigDecimal quantity = order.getDecimalField(OrderFields.PLANNED_QUANTITY); productionBalance.setField(ProductionBalanceFieldsPCWC.QUANTITY, quantity); productionBalance.setField(ProductionBalanceFieldsPCWC.TECHNOLOGY, technology); productionBalance.setField(ProductionBalanceFieldsPCWC.PRODUCTION_LINE, productionLine); costCalculationService.calculateOperationsAndProductsCosts(productionBalance); final BigDecimal productionCosts = costCalculationService.calculateProductionCost(productionBalance); final BigDecimal doneQuantity = order.getDecimalField(OrderFields.DONE_QUANTITY); costCalculationService.calculateTotalCosts(productionBalance, productionCosts, doneQuantity); BigDecimal perUnit = BigDecimal.ZERO; if (!BigDecimalUtils.valueEquals(BigDecimal.ZERO, doneQuantity)) { BigDecimal totalTechnicalProductionCosts = productionBalance .getDecimalField(ProductionBalanceFieldsPCWC.TOTAL_TECHNICAL_PRODUCTION_COSTS); perUnit = totalTechnicalProductionCosts.divide(doneQuantity, numberService.getMathContext()); } productionBalance.setField(ProductionBalanceFieldsPCWC.TOTAL_TECHNICAL_PRODUCTION_COST_PER_UNIT, numberService.setScale(perUnit)); } @Override void update(final Observable observable, final Object object); void doTheCostsPart(final Entity productionBalance); void fillFieldsAndGrids(final Entity productionBalance); }### Answer:
@Test public void shouldSetQuantityTechnologyProductionLineAndTechnicalProductionCostPerUnitFieldsAndSaveEntity() { BigDecimal quantity = BigDecimal.TEN; BigDecimal doneQuantity = BigDecimal.TEN; given(productionBalance.getDecimalField(ProductionBalanceFieldsPCWC.TOTAL_TECHNICAL_PRODUCTION_COSTS)).willReturn( BigDecimal.valueOf(100)); given(order.getDecimalField(OrderFields.PLANNED_QUANTITY)).willReturn(quantity); given(order.getDecimalField(OrderFields.DONE_QUANTITY)).willReturn(doneQuantity); given(order.getBelongsToField(OrderFields.PRODUCTION_LINE)).willReturn(productionLine); generateProductionBalanceWithCosts.doTheCostsPart(productionBalance); verify(productionBalance).setField(ProductionBalanceFieldsPCWC.QUANTITY, quantity); verify(productionBalance).setField(ProductionBalanceFieldsPCWC.TECHNOLOGY, technology); verify(productionBalance).setField(ProductionBalanceFieldsPCWC.PRODUCTION_LINE, productionLine); verify(productionBalance).setField(ProductionBalanceFieldsPCWC.TOTAL_TECHNICAL_PRODUCTION_COST_PER_UNIT, BigDecimal.TEN.setScale(5, RoundingMode.HALF_EVEN)); } |
### Question:
GenerateProductionBalanceWithCosts implements Observer { void generateBalanceWithCostsReport(final Entity productionBalance) { Locale locale = LocaleContextHolder.getLocale(); String localePrefix = "productionCounting.productionBalanceWithCosts.report.fileName"; Entity productionBalanceWithFileName = fileService.updateReportFileName(productionBalance, ProductionBalanceFields.DATE, localePrefix); String localePrefixToMatch = localePrefix; try { productionBalanceWithCostsPdfService.generateDocument(productionBalanceWithFileName, locale, localePrefixToMatch); productionBalanceWithFileName.setField(ProductionBalanceFieldsPCWC.GENERATED_WITH_COSTS, Boolean.TRUE); productionBalanceWithFileName.getDataDefinition().save(productionBalanceWithFileName); } catch (IOException e) { throw new IllegalStateException("Problem with saving productionBalanceWithCosts report", e); } catch (DocumentException e) { throw new IllegalStateException("Problem with generating productionBalanceWithCosts report", e); } } @Override void update(final Observable observable, final Object object); void doTheCostsPart(final Entity productionBalance); void fillFieldsAndGrids(final Entity productionBalance); }### Answer:
@Test public void shouldGenerateReportCorrectly() throws Exception { Locale locale = Locale.getDefault(); String localePrefix = "productionCounting.productionBalanceWithCosts.report.fileName"; Entity productionBalanceWithFileName = mock(Entity.class); given(productionBalanceWithFileName.getDataDefinition()).willReturn(productionBalanceDD); given(fileService.updateReportFileName(productionBalance, ProductionBalanceFields.DATE, localePrefix)).willReturn( productionBalanceWithFileName); generateProductionBalanceWithCosts.generateBalanceWithCostsReport(productionBalance); verify(productionBalanceWithCostsPdfService).generateDocument(productionBalanceWithFileName, locale, localePrefix); verify(productionBalanceWithFileName).setField(ProductionBalanceFieldsPCWC.GENERATED_WITH_COSTS, Boolean.TRUE); verify(productionBalanceDD).save(productionBalanceWithFileName); } |
### Question:
ProductDetailsListenersT { public final void addTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologyGroups"); String url = "../page/technologies/technologyGroupDetails.html"; view.redirectTo(url, false, true, parameters); } final void addTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); final void showTechnologiesWithProduct(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); final void showTechnologiesWithUsingProduct(final ViewDefinitionState view, final ComponentState state,
final String[] args); }### Answer:
@Test public void shouldntAddTechnologyGroupIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/technologies/technologyGroupDetails.html"; productDetailsListenersT.addTechnologyGroup(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); }
@Test public void shouldAddTechnologyGroupIfProductIsSaved() { given(product.getId()).willReturn(L_ID); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologyGroups"); String url = "../page/technologies/technologyGroupDetails.html"; productDetailsListenersT.addTechnologyGroup(view, null, null); verify(view).redirectTo(url, false, true, parameters); } |
### Question:
CostNormsForOperationService { public void copyCostValuesFromOperation(final ViewDefinitionState view, final ComponentState operationLookupState, final String[] args) { ComponentState operationLookup = view.getComponentByReference(OPERATION_FIELD); if (operationLookup.getFieldValue() == null) { if (!OPERATION_FIELD.equals(operationLookupState.getName())) { view.getComponentByReference("form").addMessage("costNormsForOperation.messages.info.missingOperationReference", INFO); } return; } Entity operation = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_OPERATION).get((Long) operationLookup.getFieldValue()); applyCostNormsFromGivenSource(view, operation); } void copyCostValuesFromOperation(final ViewDefinitionState view, final ComponentState operationLookupState,
final String[] args); void inheritOperationNormValues(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); void fillCurrencyFields(final ViewDefinitionState view); void copyCostNormsToTechnologyOperationComponent(final DataDefinition dd, final Entity technologyOperationComponent); }### Answer:
@Test public void shouldReturnWhenOperationIsNull() throws Exception { costNormsForOperationService.copyCostValuesFromOperation(view, state, null); }
@Test public void shouldApplyCostNormsForGivenSource() throws Exception { when(state.getFieldValue()).thenReturn(1L); Long operationId = 1L; when(operationDD.get(operationId)).thenReturn(operationEntity); when(operationEntity.getField("pieceworkCost")).thenReturn(obj1); when(operationEntity.getField("numberOfOperations")).thenReturn(obj2); when(operationEntity.getField("laborHourlyCost")).thenReturn(obj3); when(operationEntity.getField("machineHourlyCost")).thenReturn(obj4); costNormsForOperationService.copyCostValuesFromOperation(view, state, null); Mockito.verify(field1).setFieldValue(obj1); Mockito.verify(field2).setFieldValue(obj2); Mockito.verify(field3).setFieldValue(obj3); Mockito.verify(field4).setFieldValue(obj4); } |
### Question:
ProductDetailsListenersT { public final void showTechnologiesWithTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } Entity technologyGroup = product.getBelongsToField("technologyGroup"); if (technologyGroup == null) { return; } String technologyGroupNumber = technologyGroup.getStringField(NUMBER); Map<String, String> filters = Maps.newHashMap(); filters.put("technologyGroupNumber", technologyGroupNumber); Map<String, Object> gridOptions = Maps.newHashMap(); gridOptions.put(L_FILTERS, filters); Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologies"); String url = "../page/technologies/technologiesList.html"; view.redirectTo(url, false, true, parameters); } final void addTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); final void showTechnologiesWithProduct(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); final void showTechnologiesWithUsingProduct(final ViewDefinitionState view, final ComponentState state,
final String[] args); }### Answer:
@Test public void shouldntShowTechnologiesWithTechnologyGroupIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithTechnologyGroup(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); }
@Test public void shouldntShowTechnologiesWithTechnologyGroupIfProductIsSavedAndTechnologyGroupIsNull() { given(product.getId()).willReturn(L_ID); given(product.getBelongsToField("technologyGroup")).willReturn(null); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithTechnologyGroup(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); }
@Test public void shouldShowTechnologiesWithTechnologyGroupIfProductIsSavedAndTechnologyGroupIsntNull() { given(product.getId()).willReturn(L_ID); given(product.getBelongsToField("technologyGroup")).willReturn(technologyGroup); given(technologyGroup.getStringField(NUMBER)).willReturn(L_TECHNOLOGY_GROUP_NUMBER); filters.put("technologyGroupNumber", L_TECHNOLOGY_GROUP_NUMBER); gridOptions.put(L_FILTERS, filters); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologies"); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithTechnologyGroup(view, null, null); verify(view).redirectTo(url, false, true, parameters); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.