method2testcases
stringlengths
118
3.08k
### Question: RegexUtils { public static boolean isMobileExact(CharSequence input) { return isMatch(RegexConstants.REGEX_MOBILE_EXACT, input); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testIsMobileExact() throws Exception { assertThat(isMobileExact("11111111111")).isFalse(); assertThat(isMobileExact("13888880000")).isTrue(); }
### Question: StringUtils { public static int length(CharSequence s) { return s == null ? 0 : s.length(); } private StringUtils(); static boolean isEmpty(CharSequence s); static boolean isTrimEmpty(String s); static boolean isSpace(String s); static boolean equals(CharSequence a, CharSequence b); static boolean equalsIgnoreCase(String a, String b); static String null2Length0(String s); static int length(CharSequence s); static String upperFirstLetter(String s); static String lowerFirstLetter(String s); static String reverse(String s); static String toDBC(String s); static String toSBC(String s); }### Answer: @Test public void testLength() throws Exception { assertThat(length(null)).isEqualTo(0); assertThat(length("")).isEqualTo(0); assertThat(length("blankj")).isEqualTo(6); }
### Question: RegexUtils { public static boolean isIDCard18(CharSequence input) { return isMatch(RegexConstants.REGEX_ID_CARD18, input); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testIsIDCard() throws Exception { assertThat(isIDCard18("33698418400112523x")).isTrue(); assertThat(isIDCard18("336984184001125233")).isTrue(); assertThat(isIDCard18("336984184021125233")).isFalse(); }
### Question: RegexUtils { public static boolean isEmail(CharSequence input) { return isMatch(RegexConstants.REGEX_EMAIL, input); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testIsEmail() throws Exception { assertThat(isEmail("[email protected]")).isTrue(); assertThat(isEmail("blankj@qq")).isFalse(); }
### Question: RegexUtils { public static boolean isURL(CharSequence input) { return isMatch(RegexConstants.REGEX_URL, input); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testIsURL() throws Exception { assertThat(isURL("http: assertThat(isURL("https:blank")).isFalse(); }
### Question: RegexUtils { public static boolean isZh(CharSequence input) { return isMatch(RegexConstants.REGEX_ZH, input); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testIsChz() throws Exception { assertThat(isZh("我")).isTrue(); assertThat(isZh("wo")).isFalse(); }
### Question: RegexUtils { public static boolean isUsername(CharSequence input) { return isMatch(RegexConstants.REGEX_USERNAME, input); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testIsUsername() throws Exception { assertThat(isUsername("小明233333")).isTrue(); assertThat(isUsername("小明")).isFalse(); assertThat(isUsername("小明233333_")).isFalse(); }
### Question: RegexUtils { public static boolean isDate(CharSequence input) { return isMatch(RegexConstants.REGEX_DATE, input); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testIsDate() throws Exception { assertThat(isDate("2016-08-16")).isTrue(); assertThat(isDate("2016-02-29")).isTrue(); assertThat(isDate("2015-02-29")).isFalse(); assertThat(isDate("2016-8-16")).isFalse(); }
### Question: RegexUtils { public static boolean isIP(CharSequence input) { return isMatch(RegexConstants.REGEX_IP, input); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testIsIP() throws Exception { assertThat(isIP("255.255.255.0")).isTrue(); assertThat(isIP("256.255.255.0")).isFalse(); }
### Question: RegexUtils { public static boolean isMatch(String regex, CharSequence input) { return input != null && input.length() > 0 && Pattern.matches(regex, input); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testIsMatch() throws Exception { assertThat(isMatch("\\d?", "1")).isTrue(); assertThat(isMatch("\\d?", "a")).isFalse(); }
### Question: RegexUtils { public static List<String> getMatches(String regex, CharSequence input) { if (input == null) return null; List<String> matches = new ArrayList<>(); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { matches.add(matcher.group()); } return matches; } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testGetMatches() throws Exception { System.out.println(getMatches("b.*j", "blankj blankj")); System.out.println(getMatches("b.*?j", "blankj blankj")); }
### Question: RegexUtils { public static String[] getSplits(String input, String regex) { if (input == null) return null; return input.split(regex); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testGetSplits() throws Exception { System.out.println(Arrays.asList(getSplits("1 2 3", " "))); }
### Question: StringUtils { public static String upperFirstLetter(String s) { if (isEmpty(s) || !Character.isLowerCase(s.charAt(0))) return s; return String.valueOf((char) (s.charAt(0) - 32)) + s.substring(1); } private StringUtils(); static boolean isEmpty(CharSequence s); static boolean isTrimEmpty(String s); static boolean isSpace(String s); static boolean equals(CharSequence a, CharSequence b); static boolean equalsIgnoreCase(String a, String b); static String null2Length0(String s); static int length(CharSequence s); static String upperFirstLetter(String s); static String lowerFirstLetter(String s); static String reverse(String s); static String toDBC(String s); static String toSBC(String s); }### Answer: @Test public void testUpperFirstLetter() throws Exception { assertThat(upperFirstLetter("blankj")).isEqualTo("Blankj"); assertThat(upperFirstLetter("Blankj")).isEqualTo("Blankj"); assertThat(upperFirstLetter("1Blankj")).isEqualTo("1Blankj"); }
### Question: RegexUtils { public static String getReplaceFirst(String input, String regex, String replacement) { if (input == null) return null; return Pattern.compile(regex).matcher(input).replaceFirst(replacement); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testGetReplace() throws Exception { System.out.println(getReplaceFirst("1 2 3", " ", ", ")); }
### Question: RegexUtils { public static String getReplaceAll(String input, String regex, String replacement) { if (input == null) return null; return Pattern.compile(regex).matcher(input).replaceAll(replacement); } private RegexUtils(); static boolean isMobileSimple(CharSequence input); static boolean isMobileExact(CharSequence input); static boolean isTel(CharSequence input); static boolean isIDCard15(CharSequence input); static boolean isIDCard18(CharSequence input); static boolean isEmail(CharSequence input); static boolean isURL(CharSequence input); static boolean isZh(CharSequence input); static boolean isUsername(CharSequence input); static boolean isDate(CharSequence input); static boolean isIP(CharSequence input); static boolean isMatch(String regex, CharSequence input); static List<String> getMatches(String regex, CharSequence input); static String[] getSplits(String input, String regex); static String getReplaceFirst(String input, String regex, String replacement); static String getReplaceAll(String input, String regex, String replacement); }### Answer: @Test public void testGetReplaceAll() throws Exception { System.out.println(getReplaceAll("1 2 3", " ", ", ")); }
### Question: SPUtils { public String getString(String key) { return getString(key, null); } SPUtils(String spName); void put(String key, @Nullable String value); String getString(String key); String getString(String key, String defaultValue); void put(String key, int value); int getInt(String key); int getInt(String key, int defaultValue); void put(String key, long value); long getLong(String key); long getLong(String key, long defaultValue); void put(String key, float value); float getFloat(String key); float getFloat(String key, float defaultValue); void put(String key, boolean value); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); void put(String key, @Nullable Set<String> values); Set<String> getStringSet(String key); Set<String> getStringSet(String key, @Nullable Set<String> defaultValue); Map<String, ?> getAll(); void remove(String key); boolean contains(String key); void clear(); }### Answer: @Test public void testGetString() throws Exception { assertThat(spUtils.getString("stringKey")).isEqualTo("stringVal"); assertThat(spUtils.getString("stringKey1", "stringVal1")).isEqualTo("stringVal1"); assertThat(spUtils.getString("stringKey1")).isNull(); }
### Question: SPUtils { public int getInt(String key) { return getInt(key, -1); } SPUtils(String spName); void put(String key, @Nullable String value); String getString(String key); String getString(String key, String defaultValue); void put(String key, int value); int getInt(String key); int getInt(String key, int defaultValue); void put(String key, long value); long getLong(String key); long getLong(String key, long defaultValue); void put(String key, float value); float getFloat(String key); float getFloat(String key, float defaultValue); void put(String key, boolean value); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); void put(String key, @Nullable Set<String> values); Set<String> getStringSet(String key); Set<String> getStringSet(String key, @Nullable Set<String> defaultValue); Map<String, ?> getAll(); void remove(String key); boolean contains(String key); void clear(); }### Answer: @Test public void testGetInt() throws Exception { assertThat(spUtils.getInt("intKey")).isEqualTo(1); assertThat(spUtils.getInt("intKey1", 10086)).isEqualTo(10086); assertThat(spUtils.getInt("intKey1")).isEqualTo(-1); }
### Question: SPUtils { public long getLong(String key) { return getLong(key, -1L); } SPUtils(String spName); void put(String key, @Nullable String value); String getString(String key); String getString(String key, String defaultValue); void put(String key, int value); int getInt(String key); int getInt(String key, int defaultValue); void put(String key, long value); long getLong(String key); long getLong(String key, long defaultValue); void put(String key, float value); float getFloat(String key); float getFloat(String key, float defaultValue); void put(String key, boolean value); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); void put(String key, @Nullable Set<String> values); Set<String> getStringSet(String key); Set<String> getStringSet(String key, @Nullable Set<String> defaultValue); Map<String, ?> getAll(); void remove(String key); boolean contains(String key); void clear(); }### Answer: @Test public void testGetLong() throws Exception { assertThat(spUtils.getLong("longKey")).isEqualTo(1L); assertThat(spUtils.getLong("longKey1", 10086L)).isEqualTo(10086L); assertThat(spUtils.getLong("longKey1")).isEqualTo(-1L); }
### Question: SPUtils { public float getFloat(String key) { return getFloat(key, -1f); } SPUtils(String spName); void put(String key, @Nullable String value); String getString(String key); String getString(String key, String defaultValue); void put(String key, int value); int getInt(String key); int getInt(String key, int defaultValue); void put(String key, long value); long getLong(String key); long getLong(String key, long defaultValue); void put(String key, float value); float getFloat(String key); float getFloat(String key, float defaultValue); void put(String key, boolean value); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); void put(String key, @Nullable Set<String> values); Set<String> getStringSet(String key); Set<String> getStringSet(String key, @Nullable Set<String> defaultValue); Map<String, ?> getAll(); void remove(String key); boolean contains(String key); void clear(); }### Answer: @Test public void testGetFloat() throws Exception { assertThat(spUtils.getFloat("floatKey") - 1.f).isWithin(0.f); assertThat(spUtils.getFloat("floatKey1", 10086f) - 10086f).isWithin(0.f); assertThat(spUtils.getFloat("floatKey1") + 1.f).isWithin(0.f); }
### Question: SPUtils { public boolean getBoolean(String key) { return getBoolean(key, false); } SPUtils(String spName); void put(String key, @Nullable String value); String getString(String key); String getString(String key, String defaultValue); void put(String key, int value); int getInt(String key); int getInt(String key, int defaultValue); void put(String key, long value); long getLong(String key); long getLong(String key, long defaultValue); void put(String key, float value); float getFloat(String key); float getFloat(String key, float defaultValue); void put(String key, boolean value); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); void put(String key, @Nullable Set<String> values); Set<String> getStringSet(String key); Set<String> getStringSet(String key, @Nullable Set<String> defaultValue); Map<String, ?> getAll(); void remove(String key); boolean contains(String key); void clear(); }### Answer: @Test public void testGetBoolean() throws Exception { assertThat(spUtils.getBoolean("booleanKey")).isTrue(); assertThat(spUtils.getBoolean("booleanKey1", true)).isTrue(); assertThat(spUtils.getBoolean("booleanKey1")).isFalse(); }
### Question: SPUtils { public Map<String, ?> getAll() { return sp.getAll(); } SPUtils(String spName); void put(String key, @Nullable String value); String getString(String key); String getString(String key, String defaultValue); void put(String key, int value); int getInt(String key); int getInt(String key, int defaultValue); void put(String key, long value); long getLong(String key); long getLong(String key, long defaultValue); void put(String key, float value); float getFloat(String key); float getFloat(String key, float defaultValue); void put(String key, boolean value); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); void put(String key, @Nullable Set<String> values); Set<String> getStringSet(String key); Set<String> getStringSet(String key, @Nullable Set<String> defaultValue); Map<String, ?> getAll(); void remove(String key); boolean contains(String key); void clear(); }### Answer: @Test public void testGetAll() throws Exception { Map<String, ?> map = spUtils.getAll(); for (Map.Entry<String, ?> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } }
### Question: SPUtils { public void remove(String key) { editor.remove(key).apply(); } SPUtils(String spName); void put(String key, @Nullable String value); String getString(String key); String getString(String key, String defaultValue); void put(String key, int value); int getInt(String key); int getInt(String key, int defaultValue); void put(String key, long value); long getLong(String key); long getLong(String key, long defaultValue); void put(String key, float value); float getFloat(String key); float getFloat(String key, float defaultValue); void put(String key, boolean value); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); void put(String key, @Nullable Set<String> values); Set<String> getStringSet(String key); Set<String> getStringSet(String key, @Nullable Set<String> defaultValue); Map<String, ?> getAll(); void remove(String key); boolean contains(String key); void clear(); }### Answer: @Test public void testRemove() throws Exception { spUtils.remove("stringKey"); testGetAll(); }
### Question: SPUtils { public boolean contains(String key) { return sp.contains(key); } SPUtils(String spName); void put(String key, @Nullable String value); String getString(String key); String getString(String key, String defaultValue); void put(String key, int value); int getInt(String key); int getInt(String key, int defaultValue); void put(String key, long value); long getLong(String key); long getLong(String key, long defaultValue); void put(String key, float value); float getFloat(String key); float getFloat(String key, float defaultValue); void put(String key, boolean value); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); void put(String key, @Nullable Set<String> values); Set<String> getStringSet(String key); Set<String> getStringSet(String key, @Nullable Set<String> defaultValue); Map<String, ?> getAll(); void remove(String key); boolean contains(String key); void clear(); }### Answer: @Test public void testContains() throws Exception { assertThat(spUtils.contains("stringKey")).isTrue(); assertThat(spUtils.contains("string")).isFalse(); }
### Question: StringUtils { public static String lowerFirstLetter(String s) { if (isEmpty(s) || !Character.isUpperCase(s.charAt(0))) return s; return String.valueOf((char) (s.charAt(0) + 32)) + s.substring(1); } private StringUtils(); static boolean isEmpty(CharSequence s); static boolean isTrimEmpty(String s); static boolean isSpace(String s); static boolean equals(CharSequence a, CharSequence b); static boolean equalsIgnoreCase(String a, String b); static String null2Length0(String s); static int length(CharSequence s); static String upperFirstLetter(String s); static String lowerFirstLetter(String s); static String reverse(String s); static String toDBC(String s); static String toSBC(String s); }### Answer: @Test public void testLowerFirstLetter() throws Exception { assertThat(lowerFirstLetter("blankj")).isEqualTo("blankj"); assertThat(lowerFirstLetter("Blankj")).isEqualTo("blankj"); assertThat(lowerFirstLetter("1blankj")).isEqualTo("1blankj"); }
### Question: SPUtils { public void clear() { editor.clear().apply(); } SPUtils(String spName); void put(String key, @Nullable String value); String getString(String key); String getString(String key, String defaultValue); void put(String key, int value); int getInt(String key); int getInt(String key, int defaultValue); void put(String key, long value); long getLong(String key); long getLong(String key, long defaultValue); void put(String key, float value); float getFloat(String key); float getFloat(String key, float defaultValue); void put(String key, boolean value); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); void put(String key, @Nullable Set<String> values); Set<String> getStringSet(String key); Set<String> getStringSet(String key, @Nullable Set<String> defaultValue); Map<String, ?> getAll(); void remove(String key); boolean contains(String key); void clear(); }### Answer: @Test public void testClear() throws Exception { spUtils.clear(); testGetAll(); }
### Question: SDCardUtils { public static boolean isSDCardEnable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } private SDCardUtils(); static boolean isSDCardEnable(); static String getSDCardPath(); static String getDataPath(); @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) static String getFreeSpace(); @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) static String getSDCardInfo(); }### Answer: @Test public void testIsSDCardEnable() throws Exception { System.out.println(SDCardUtils.isSDCardEnable()); }
### Question: SDCardUtils { public static String getSDCardPath() { if (!isSDCardEnable()) return null; String cmd = "cat /proc/mounts"; Runtime run = Runtime.getRuntime(); BufferedReader bufferedReader = null; try { Process p = run.exec(cmd); bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getInputStream()))); String lineStr; while ((lineStr = bufferedReader.readLine()) != null) { if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) { String[] strArray = lineStr.split(" "); if (strArray.length >= 5) { return strArray[1].replace("/.android_secure", "") + File.separator; } } if (p.waitFor() != 0 && p.exitValue() == 1) { break; } } } catch (Exception e) { e.printStackTrace(); } finally { CloseUtils.closeIO(bufferedReader); } return Environment.getExternalStorageDirectory().getPath() + File.separator; } private SDCardUtils(); static boolean isSDCardEnable(); static String getSDCardPath(); static String getDataPath(); @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) static String getFreeSpace(); @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) static String getSDCardInfo(); }### Answer: @Test public void testGetSDCardPath() throws Exception { System.out.println(SDCardUtils.getSDCardPath()); }
### Question: StringUtils { public static String reverse(String s) { int len = length(s); if (len <= 1) return s; int mid = len >> 1; char[] chars = s.toCharArray(); char c; for (int i = 0; i < mid; ++i) { c = chars[i]; chars[i] = chars[len - i - 1]; chars[len - i - 1] = c; } return new String(chars); } private StringUtils(); static boolean isEmpty(CharSequence s); static boolean isTrimEmpty(String s); static boolean isSpace(String s); static boolean equals(CharSequence a, CharSequence b); static boolean equalsIgnoreCase(String a, String b); static String null2Length0(String s); static int length(CharSequence s); static String upperFirstLetter(String s); static String lowerFirstLetter(String s); static String reverse(String s); static String toDBC(String s); static String toSBC(String s); }### Answer: @Test public void testReverse() throws Exception { assertThat(reverse("blankj")).isEqualTo("jknalb"); assertThat(reverse("blank")).isEqualTo("knalb"); assertThat(reverse("测试中文")).isEqualTo("文中试测"); assertThat(reverse(null)).isNull(); }
### Question: StringUtils { public static String toDBC(String s) { if (isEmpty(s)) return s; char[] chars = s.toCharArray(); for (int i = 0, len = chars.length; i < len; i++) { if (chars[i] == 12288) { chars[i] = ' '; } else if (65281 <= chars[i] && chars[i] <= 65374) { chars[i] = (char) (chars[i] - 65248); } else { chars[i] = chars[i]; } } return new String(chars); } private StringUtils(); static boolean isEmpty(CharSequence s); static boolean isTrimEmpty(String s); static boolean isSpace(String s); static boolean equals(CharSequence a, CharSequence b); static boolean equalsIgnoreCase(String a, String b); static String null2Length0(String s); static int length(CharSequence s); static String upperFirstLetter(String s); static String lowerFirstLetter(String s); static String reverse(String s); static String toDBC(String s); static String toSBC(String s); }### Answer: @Test public void testToDBC() throws Exception { assertThat(toDBC(" ,.&")).isEqualTo(" ,.&"); }
### Question: IssueEventHandler implements EventHandler { @Override public void processEvents(final List<Event> eventList, final Set<String> dashboardIds) { final List<String> idList = eventList.stream() .map(Event::getCollectionId) .map(String.class::cast) .collect(Collectors.toList()); if (idList.contains(null)) { connectionHandler.sendEventUpdateMessageToAll(EventType.ISSUE); } else { final Iterable<Issue> issues = issueService.getIssuesById(idList); final Predicate<Dashboard> filterDashboards = dashboard -> StreamSupport.stream(issues.spliterator(), false) .anyMatch(issue -> CollectionUtils.containsAny(issue.getKeywords(), dashboard.getBoards())); eventsHelper.processEvents(dashboardIds, filterDashboards, EventType.ISSUE); } } @Autowired IssueEventHandler( final ConnectionHandler connectionHandler, final IssueService issueService, final ProcessEventsHelper eventsHelper ); @Override void processEvents(final List<Event> eventList, final Set<String> dashboardIds); }### Answer: @Test public void testDeletedEvents() { when(dashboardService.getDashboardWithNames(anyList())).thenReturn(Collections.emptyList()); eventHandler.processEvents(Collections.singletonList(new Event()), Collections.emptySet()); verify(connectionHandler, times(1)).sendEventUpdateMessageToAll(EventType.ISSUE); }
### Question: DashboardRepositoryImpl implements DashboardRepositoryCustom { @Override public List<Dashboard> getActiveDashboards() { return getDashboardsNotInStatus(DELETED, TRANSIENT); } @Override List<Dashboard> getActiveAndTransientDashboards(); @Override List<Dashboard> getActiveDashboards(); @Override void saveFile(final InputStream image, final String name); @Override InputStreamResource readFile(final String name); }### Answer: @Ignore @Test public void transientAndDeletedDashboardsAreNotReturnedTest() { final List<Dashboard> activeDashboards = dashboardRepository.getActiveDashboards(); final List<String> dashboardNames = activeDashboards .stream() .map(Dashboard::getName) .collect(Collectors.toList()); assertTrue(dashboardNames.contains("regularDashboard")); assertTrue(dashboardNames.contains("nullStatusDashboard")); assertEquals(activeDashboards.size(), 2); }
### Question: IssueRepositoryImpl implements IssueRepositoryCustom { @Override public List<String> programIncrementBoardFeatures( final List<String> boards, final List<String> programIncrementFeatures ) { final Aggregation agg = newAggregation( match(Criteria .where("parentsKeys").in(programIncrementFeatures) .and("keywords").in(boards) ), unwind("parentsKeys"), group() .addToSet("parentsKeys") .as("features"), project("features") .andExclude("_id") ); final AggregationResults<ProgramIncrementBoardFeatures> aggregationResult = mongoTemplate.aggregate(agg, "issue", ProgramIncrementBoardFeatures.class); return aggregationResult.getUniqueMappedResult() != null ? aggregationResult.getUniqueMappedResult().features : new ArrayList<>(); } @Override double getBacklogEstimateByKeywords(final List<String> boards); @Override SprintStats getSprintStatsByKeywords(final List<String> boards); @Override List<String> programIncrementBoardFeatures( final List<String> boards, final List<String> programIncrementFeatures ); @Override ProgramIncrementNamesAggregationResult getProductIncrementFromPiPattern(final Pattern pi); }### Answer: @Test public void testFeatureAndPIComeFromTeam() { final List<String> boardPIFeatures = issueRepository.programIncrementBoardFeatures( Collections.singletonList("mirrorgate"), Arrays.asList("issue1", "issue2") ); assertEquals(2, boardPIFeatures.size()); }
### Question: IssueRepositoryImpl implements IssueRepositoryCustom { @Override public ProgramIncrementNamesAggregationResult getProductIncrementFromPiPattern(final Pattern pi) { final Aggregation agg = newAggregation( match(Criteria .where("type").is(IssueType.FEATURE.getName()) ), project("piNames").andExclude("_id"), unwind("piNames"), match(Criteria .where("piNames").is(pi) ), group().addToSet("piNames").as("piNames") ); final AggregationResults<ProgramIncrementNamesAggregationResult> aggregationResult = mongoTemplate.aggregate(agg, "issue", ProgramIncrementNamesAggregationResult.class); return aggregationResult.getUniqueMappedResult(); } @Override double getBacklogEstimateByKeywords(final List<String> boards); @Override SprintStats getSprintStatsByKeywords(final List<String> boards); @Override List<String> programIncrementBoardFeatures( final List<String> boards, final List<String> programIncrementFeatures ); @Override ProgramIncrementNamesAggregationResult getProductIncrementFromPiPattern(final Pattern pi); }### Answer: @Test public void testAggregationWithResults() { final ProgramIncrementNamesAggregationResult piNames = issueRepository.getProductIncrementFromPiPattern( Pattern.compile("^PI.*$") ); assertEquals(piNames.getPiNames().size(), 5); assertTrue(piNames.getPiNames().contains("PI1")); assertTrue(piNames.getPiNames().contains("PI2")); assertTrue(piNames.getPiNames().contains("PI3")); assertTrue(piNames.getPiNames().contains("PI4")); assertTrue(piNames.getPiNames().contains("PI5")); } @Test public void testAggregationWithoutResults() { final ProgramIncrementNamesAggregationResult piNames = issueRepository.getProductIncrementFromPiPattern( Pattern.compile("aaa") ); assertNull(piNames); }
### Question: EventScheduler { @Scheduled(fixedDelayString = "${events.scheduler.delay.millis}") void checkEventUpdates() { LOG.debug("Processing events for timestamp {}", schedulerTimestamp); final Set<String> dashboardIds = handler.getDashboardsWithSession(); if (dashboardIds != null) { LOG.debug("Active dashboards {}", dashboardIds.size()); } if (! Objects.requireNonNull(dashboardIds).isEmpty()) { final List<Event> unprocessedEvents = eventService.getEventsSinceTimestamp(schedulerTimestamp); if (! unprocessedEvents.isEmpty()) { unprocessedEvents.stream() .collect(Collectors.groupingBy(Event::getEventType)) .forEach((key, value) -> beanFactory.getBean(key.getValue(), EventHandler.class) .processEvents(value, dashboardIds)); schedulerTimestamp = unprocessedEvents.get(unprocessedEvents.size() - 1).getTimestamp(); LOG.debug("Modified timestamp: {}", schedulerTimestamp); } } } @Autowired EventScheduler( final EventService eventService, final ConnectionHandler handler, final BeanFactory beanFactory ); @PostConstruct void initSchedulerTimestamp(); }### Answer: @Test public void testSchedulerTimestampIsModified() { when(eventService.getEventsSinceTimestamp(anyLong())) .thenReturn(Arrays.asList(createBuildEvent(), createIssueEvent())); when(eventService.getLastEvent()).thenReturn(null); when(eventsHandler.getDashboardsWithSession()).thenReturn(new HashSet<>(Collections.singletonList("123"))); eventScheduler.checkEventUpdates(); assertTrue(outputCapture.toString().contains("1234567")); }
### Question: DataServiceBase implements TableDataService { @Override public List<Map<String, String>> getPageEntries(PaginationCriteria paginationCriteria) throws TableDataException { List<T> data = getData(paginationCriteria); log.debug("Table data retrieved..."); List<Map<String, String>> records = new ArrayList<>(data.size()); try { data.forEach(i -> { Map<String, Object> m = objectMapper.convertValue(i, Map.class); records.add(m.entrySet().stream() .collect(Collectors.toMap(k -> k.getKey(), v -> v.getValue().toString()))); }); log.debug("Data map generated..."); } catch (Exception e) { log.error("Error fetching page entries.", e); throw new TableDataException("", e); } return records; } @Override List<Map<String, String>> getPageEntries(PaginationCriteria paginationCriteria); }### Answer: @Test void getPageEntries() throws TableDataException { List<Map<String, String>> data = dataService.getPageEntries(null); assertEquals(5, data.size()); assertEquals("Lisa", data.get(0).get("name")); assertEquals("2", data.get(1).get("id")); assertEquals("38", data.get(2).get("age")); }
### Question: PingResponseWriter { public void write(PrintWriter writer) { writer.write("pong"); } void write(PrintWriter writer); }### Answer: @Test public void writeResponse() throws Exception { underTest.write(printWriter); verify(printWriter).write("pong"); }
### Question: JmsTemplateBeanDefinitionFactory { public AbstractBeanDefinition create(String connectionFactoryBeanName) { return genericBeanDefinition(JmsTemplate.class) .addConstructorArgReference(connectionFactoryBeanName) .getBeanDefinition(); } AbstractBeanDefinition create(String connectionFactoryBeanName); String createBeanName(String brokerName); static final String JMS_TEMPLATE_BEAN_NAME_PREFIX; }### Answer: @Test public void createJmsTemplateBeanDefinition() { final AbstractBeanDefinition abstractBeanDefinition = underTest.create("internal-jmsConnectionFactory"); Assert.assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(JmsTemplate.class)); Assert.assertThat(abstractBeanDefinition.getConstructorArgumentValues().getIndexedArgumentValues().size(), is(1)); Assert.assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(0, ConnectionFactory.class).getValue(), is(equalTo(new RuntimeBeanReference("internal-jmsConnectionFactory")))); }
### Question: JmsTemplateBeanDefinitionFactory { public String createBeanName(String brokerName) { return JMS_TEMPLATE_BEAN_NAME_PREFIX + brokerName; } AbstractBeanDefinition create(String connectionFactoryBeanName); String createBeanName(String brokerName); static final String JMS_TEMPLATE_BEAN_NAME_PREFIX; }### Answer: @Test public void createJmsTemplateBeanName() { assertThat(underTest.createBeanName("internal"), Matchers.is("jmsTemplate-internal")); }
### Question: SpringMessageSender implements MessageSender { @Override public void send(FailedMessage failedMessage) { LOGGER.debug("Resending FailedMessage: {}", failedMessage.getFailedMessageId()); jmsTemplate.send( failedMessage .getDestination() .getName() .orElseThrow(destinationMissingFor(failedMessage.getFailedMessageId())), failedMessageCreatorFactory.create(failedMessage) ); } @SuppressWarnings("unused") SpringMessageSender(JmsTemplate jmsTemplate); SpringMessageSender(FailedMessageCreatorFactory failedMessageCreatorFactory, JmsTemplate jmsTemplate); @Override void send(FailedMessage failedMessage); }### Answer: @Test public void successfullySendMessage() throws Exception { when(failedMessage.getDestination()).thenReturn(aDestination("some-destination")); underTest.send(failedMessage); verify(jmsTemplate).send("some-destination", failedMessageCreator); } @Test(expected = DestinationException.class) public void destinationIsMissing() { when(failedMessage.getDestination()).thenReturn(aDestination(null)); underTest.send(failedMessage); }
### Question: FailedMessageCreator implements MessageCreator { @Override public Message createMessage(Session session) throws JMSException { TextMessage textMessage = session.createTextMessage(); for (JmsMessageTransformer<TextMessage, FailedMessage> jmsMessageTransformer : jmsMessageTransformers) { jmsMessageTransformer.transform(textMessage, failedMessage); } return textMessage; } FailedMessageCreator(FailedMessage failedMessage); FailedMessageCreator(FailedMessage failedMessage, List<JmsMessageTransformer<TextMessage, FailedMessage>> jmsMessageTransformers); @Override Message createMessage(Session session); }### Answer: @Test public void createJmsMessage() throws Exception { when(session.createTextMessage()).thenReturn(textMessage); FailedMessageCreator underTest = new FailedMessageCreator(newFailedMessage() .withContent("Hello") .withProperty("foo", "bar") .build() ); assertThat(underTest.createMessage(session), Matchers.is(textMessage)); verify(textMessage).setText("Hello"); verify(textMessage).setObjectProperty("foo", "bar"); }
### Question: PropertyMatchesPredicate implements FailedMessagePredicate { @Override public boolean test(FailedMessage failedMessage) { return pattern .matcher(getPropertyAsString(failedMessage)) .matches(); } PropertyMatchesPredicate(@JsonProperty("name") String name, @JsonProperty("regex") String regex); @Override boolean test(FailedMessage failedMessage); @Override Description describe(Description description); @Override String toString(); }### Answer: @Test public void propertyMatchesPattern() { when(failedMessage.getProperty("foo")).thenReturn("some.property.value"); underTest = new PropertyMatchesPredicate("foo", "^some\\.property.*"); assertThat(underTest.test(failedMessage), is(true)); } @Test public void propertyDoesNotMatchPattern() { when(failedMessage.getProperty("foo")).thenReturn("some.property.value"); underTest = new PropertyMatchesPredicate("foo", "^some\\.property"); assertThat(underTest.test(failedMessage), is(false)); } @Test public void propertyValueIsNull() { when(failedMessage.getProperty("foo")).thenReturn(null); underTest = new PropertyMatchesPredicate("foo", "^some\\.property"); assertThat(underTest.test(failedMessage), is(false)); } @Test public void propertyIsABoolean() { when(failedMessage.getProperty("aBoolean")).thenReturn(true); underTest = new PropertyMatchesPredicate("aBoolean", "true"); assertThat(underTest.test(failedMessage), is(true)); } @Test public void propertyIsANumber() { when(failedMessage.getProperty("aNumber")).thenReturn(12345); underTest = new PropertyMatchesPredicate("aNumber", "^12345$"); assertThat(underTest.test(failedMessage), is(true)); }
### Question: FailedMessageConverter implements DocumentWithIdConverter<FailedMessage, FailedMessageId> { @Override public FailedMessage convertToObject(Document document) { if (document == null) { return null; } return newFailedMessage() .withFailedMessageId(getFailedMessageId(document)) .withJmsMessageId(getJmsMessageId(document)) .withDestination(getDestination(document)) .withSentDateTime(getSentDateTime(document)) .withFailedDateTime(getFailedDateTime(document)) .withContent(getContent(document)) .withStatusHistoryEvent(getStatusHistoryEvent(document)) .withProperties(propertiesMongoMapper.convertToObject(document.getString(PROPERTIES))) .withLabels(getLabels(document)) .build(); } FailedMessageConverter(DocumentConverter<Destination> destinationDocumentConverter, DocumentConverter<StatusHistoryEvent> statusHistoryEventDocumentConverter, ObjectConverter<Map<String, Object>, String> propertiesMongoMapper); @Override FailedMessage convertToObject(Document document); StatusHistoryEvent getStatusHistoryEvent(Document document); FailedMessageId getFailedMessageId(Document document); Destination getDestination(Document document); String getContent(Document document); Instant getFailedDateTime(Document document); Instant getSentDateTime(Document document); @Override Document convertFromObject(FailedMessage item); Document convertForUpdate(FailedMessage item); @Override Document createId(FailedMessageId failedMessageId); static final String DESTINATION; static final String SENT_DATE_TIME; static final String FAILED_DATE_TIME; static final String CONTENT; static final String PROPERTIES; static final String STATUS_HISTORY; static final String LABELS; static final String JMS_MESSAGE_ID; }### Answer: @Test public void mapNullDocumentToFailedMessage() { assertThat(underTest.convertToObject(null), is(nullValue())); }
### Question: AndPredicate implements FailedMessagePredicate { @Override public boolean test(FailedMessage failedMessage) { return predicates .stream() .allMatch(p -> p.test(failedMessage)); } AndPredicate(@JsonProperty("predicates") List<FailedMessagePredicate> predicates); @Override boolean test(FailedMessage failedMessage); List<FailedMessagePredicate> getPredicates(); @Override Description describe(Description description); AndPredicate and(FailedMessagePredicate failedMessagePredicate); @Override String toString(); static AndPredicate and(FailedMessagePredicate lhs, FailedMessagePredicate rhs); }### Answer: @Test public void resultIsFalseWhen1stPredicateIsTrue2ndPredicteIsFalse() { when(failedMessagePredicate1.test(failedMessage)).thenReturn(true); when(failedMessagePredicate2.test(failedMessage)).thenReturn(false); assertThat(underTest.test(failedMessage), is(false)); verify(failedMessagePredicate1).test(failedMessage); verify(failedMessagePredicate2).test(failedMessage); } @Test public void resultIsAlwaysFalseWhen1stPredicateIsFalse() { when(failedMessagePredicate1.test(failedMessage)).thenReturn(false); when(failedMessagePredicate2.test(failedMessage)).thenReturn(true); assertThat(underTest.test(failedMessage), is(false)); verify(failedMessagePredicate1).test(failedMessage); verifyZeroInteractions(failedMessagePredicate2); } @Test public void resultIsTrueWhenAllPredicatesReturnTrue() { when(failedMessagePredicate1.test(failedMessage)).thenReturn(true); when(failedMessagePredicate2.test(failedMessage)).thenReturn(true); assertThat(underTest.test(failedMessage), is(true)); verify(failedMessagePredicate1).test(failedMessage); verify(failedMessagePredicate2).test(failedMessage); }
### Question: AndPredicate implements FailedMessagePredicate { public List<FailedMessagePredicate> getPredicates() { return new ArrayList<>(predicates); } AndPredicate(@JsonProperty("predicates") List<FailedMessagePredicate> predicates); @Override boolean test(FailedMessage failedMessage); List<FailedMessagePredicate> getPredicates(); @Override Description describe(Description description); AndPredicate and(FailedMessagePredicate failedMessagePredicate); @Override String toString(); static AndPredicate and(FailedMessagePredicate lhs, FailedMessagePredicate rhs); }### Answer: @Test public void canSerialiseAndDeserialisePredicate() throws IOException { ObjectMapper objectMapper = new JacksonConfiguration().objectMapper(new InjectableValues.Std()); objectMapper.registerSubtypes(BooleanPredicate.class); final AndPredicate underTest = objectMapper.readValue( objectMapper.writeValueAsString(new AndPredicate(singletonList(alwaysTruePredicate))), AndPredicate.class ); assertThat(underTest.getPredicates(), contains(alwaysTruePredicate)); }
### Question: AndPredicate implements FailedMessagePredicate { @Override public Description describe(Description description) { Description finalDescription = description.append("( "); final Iterator<FailedMessagePredicate> iterator = predicates.iterator(); while (iterator.hasNext()) { finalDescription = iterator.next().describe(finalDescription); if (iterator.hasNext()) { finalDescription = finalDescription.append(" AND "); } } return finalDescription.append(" )"); } AndPredicate(@JsonProperty("predicates") List<FailedMessagePredicate> predicates); @Override boolean test(FailedMessage failedMessage); List<FailedMessagePredicate> getPredicates(); @Override Description describe(Description description); AndPredicate and(FailedMessagePredicate failedMessagePredicate); @Override String toString(); static AndPredicate and(FailedMessagePredicate lhs, FailedMessagePredicate rhs); }### Answer: @Test public void describeTest() { when(failedMessagePredicate1.describe(any(StringDescription.class))).thenAnswer(withDescription("predicate1")); when(failedMessagePredicate2.describe(any(StringDescription.class))).thenAnswer(withDescription("predicate2")); assertThat(underTest.describe(new StringDescription()).getOutput(), is("( predicate1 AND predicate2 )")); }
### Question: AndPredicate implements FailedMessagePredicate { @Override public String toString() { return describe(new StringDescription()).toString(); } AndPredicate(@JsonProperty("predicates") List<FailedMessagePredicate> predicates); @Override boolean test(FailedMessage failedMessage); List<FailedMessagePredicate> getPredicates(); @Override Description describe(Description description); AndPredicate and(FailedMessagePredicate failedMessagePredicate); @Override String toString(); static AndPredicate and(FailedMessagePredicate lhs, FailedMessagePredicate rhs); }### Answer: @Test public void toStringTest() { when(failedMessagePredicate1.describe(any(StringDescription.class))).thenAnswer(withDescription("predicate1")); when(failedMessagePredicate2.describe(any(StringDescription.class))).thenAnswer(withDescription("predicate2")); assertThat(underTest.toString(), is("( predicate1 AND predicate2 )")); }
### Question: PropertyEqualToPredicate implements FailedMessagePredicate { @Override public boolean test(FailedMessage failedMessage) { return this.value.equals(failedMessage.getProperty(name)); } PropertyEqualToPredicate(@JsonProperty("name") String name, @JsonProperty("value") Object value); @Override boolean test(FailedMessage failedMessage); @Override Description describe(Description description); @Override String toString(); }### Answer: @Test public void propertiesMatch() { when(failedMessage.getProperty("foo")).thenReturn("bar"); assertThat(underTest.test(failedMessage), is(true)); } @Test public void propertiesDoNotMatch() { when(failedMessage.getProperty("foo")).thenReturn("rab"); assertThat(underTest.test(failedMessage), is(false)); } @Test public void propertyDoesNotExist() { when(failedMessage.getProperty("foo")).thenReturn(null); assertThat(underTest.test(failedMessage), is(false)); }
### Question: MongoStatusHistoryQueryBuilder { public Document currentStatusEqualTo(Status status) { return new Document(STATUS_HISTORY + ".0." + STATUS, status.name()); } Document currentStatusEqualTo(Status status); Document currentStatusNotEqualTo(Status status); Document currentStatusIn(Set<Status> statuses); Document currentStatusIn(Document query, Set<Status> statuses); }### Answer: @Test public void currentStatusEqualToGivenStatus() { assertThat(underTest.currentStatusEqualTo(FAILED), hasField(STATUS_HISTORY + ".0." + STATUS, equalTo(FAILED.name()))); }
### Question: DestinationEqualsPredicate implements FailedMessagePredicate { @Override public boolean test(FailedMessage failedMessage) { return destination.equals(failedMessage.getDestination().getName()); } DestinationEqualsPredicate(@JsonProperty("destination") Optional<String> destination); @Override boolean test(FailedMessage failedMessage); @Override Description describe(Description description); @Override String toString(); }### Answer: @Test public void nameOfDestinationMatches() { when(destination.getName()).thenReturn(Optional.of("some-destination")); assertThat(underTest.test(failedMessage), Matchers.is(true)); } @Test public void nameOfDestinationIsEmpty() { when(destination.getName()).thenReturn(Optional.empty()); assertThat(underTest.test(failedMessage), Matchers.is(false)); } @Test public void nameOfDestinationIDoesNotMatch() { when(destination.getName()).thenReturn(Optional.of("another-destination")); assertThat(underTest.test(failedMessage), Matchers.is(false)); }
### Question: DestinationEqualsPredicate implements FailedMessagePredicate { @Override public Description describe(Description description) { return description.append("destination ").append(destination.map(d -> "= '" + d + "'").orElse("is empty")); } DestinationEqualsPredicate(@JsonProperty("destination") Optional<String> destination); @Override boolean test(FailedMessage failedMessage); @Override Description describe(Description description); @Override String toString(); }### Answer: @Test public void describeWithAnEmptyDestination() { underTest = new DestinationEqualsPredicate(Optional.empty()); final Description<String> description = underTest.describe(new StringDescription()); assertThat(description.getOutput(), is("destination is empty")); }
### Question: PropertyExistsPredicate implements FailedMessagePredicate { @Override public boolean test(FailedMessage failedMessage) { return failedMessage.getProperties().containsKey(propertyName); } PropertyExistsPredicate(@JsonProperty("propertyName") String propertyName); @Override boolean test(FailedMessage failedMessage); @Override Description describe(Description description); @Override String toString(); }### Answer: @Test public void propertyExists() { when(failedMessage.getProperties()).thenReturn(Collections.singletonMap("foo", "bar")); assertThat(underTest.test(failedMessage), is(true)); } @Test public void propertyDoesNotExist() { when(failedMessage.getProperties()).thenReturn(Collections.emptyMap()); assertThat(underTest.test(failedMessage), is(false)); }
### Question: ContentEqualToPredicate implements FailedMessagePredicate { @Override public boolean test(FailedMessage failedMessage) { return content.equals(failedMessage.getContent()); } ContentEqualToPredicate(@JsonProperty("content") String content); @Override boolean test(FailedMessage failedMessage); @Override Description describe(Description description); @Override String toString(); }### Answer: @Test public void contentInMessageIsNull() { when(failedMessage.getContent()).thenReturn(null); assertThat(underTest.test(failedMessage), is(false)); } @Test public void contentDoesNotMatch() { when(failedMessage.getContent()).thenReturn("bar"); assertThat(underTest.test(failedMessage), is(false)); } @Test public void contentMatches() { when(failedMessage.getContent()).thenReturn("foo"); assertThat(underTest.test(failedMessage), is(true)); }
### Question: MongoStatusHistoryQueryBuilder { public Document currentStatusIn(Set<Status> statuses) { return currentStatusIn(new Document(), statuses); } Document currentStatusEqualTo(Status status); Document currentStatusNotEqualTo(Status status); Document currentStatusIn(Set<Status> statuses); Document currentStatusIn(Document query, Set<Status> statuses); }### Answer: @Test public void currentStatusIsOneOfTheGivenStatuses() { assertThat(underTest.currentStatusIn(immutableEnumSet(FAILED, CLASSIFIED)), hasField(STATUS_HISTORY + ".0." + STATUS, hasField(IN, contains(FAILED.name(), CLASSIFIED.name())))); } @Test public void currentStatusIsOneOfTheGivenStatusesWhenDocumentPassedIn() { Document document = new Document(); DocumentMatcher expectedDocument = hasField(STATUS_HISTORY + ".0." + STATUS, hasField(IN, contains(FAILED.name(), CLASSIFIED.name()))); Document actualDocument = underTest.currentStatusIn(document, immutableEnumSet(FAILED, CLASSIFIED)); assertThat(actualDocument, expectedDocument); assertThat(actualDocument, is(document)); }
### Question: ContentContainsJsonPath implements FailedMessagePredicate { @Override public boolean test(FailedMessage failedMessage) { if (StringUtils.isNotEmpty(failedMessage.getContent())) { try { final Object object = parseContext.parse(failedMessage.getContent()).read(jsonPath); if (object instanceof JSONArray) { return !((JSONArray)object).isEmpty(); } else { return true; } } catch (PathNotFoundException e) { return false; } } return false; } ContentContainsJsonPath(@JsonProperty("jsonPath") String jsonPath); @Override boolean test(FailedMessage failedMessage); @Override Description describe(Description description); @Override String toString(); }### Answer: @Test public void searchSingleFieldThatDoesNotExist() { underTest = new ContentContainsJsonPath("$.location"); assertThat(underTest.test(failedMessage), is(false)); } @Test public void searchSingleFieldThatDoesExist() { underTest = new ContentContainsJsonPath("$.expensive"); assertThat(underTest.test(failedMessage), is(true)); } @Test public void searchSingleFieldThatDoesExistWhereValueIsNull() { underTest = new ContentContainsJsonPath("$.store.bicycle.model"); assertThat(underTest.test(failedMessage), is(true)); } @Test public void searchArrayForFieldThatDoesExist() { underTest = new ContentContainsJsonPath("$.store.book[*].author"); assertThat(underTest.test(failedMessage), is(true)); } @Test public void searchArrayForFieldThatDoesExistWhereValuesAreNull() { underTest = new ContentContainsJsonPath("$.store.book[*].publicationDate"); assertThat(underTest.test(failedMessage), is(true)); } @Test public void searchArrayForFieldThatDoesNotExist() { underTest = new ContentContainsJsonPath("$.store.book[*].breakfast"); assertThat(underTest.test(failedMessage), is(false)); } @Test public void messageContentIsNull() { when(failedMessage.getContent()).thenReturn(null); underTest = new ContentContainsJsonPath("$.store.expensive"); assertThat(underTest.test(failedMessage), is(false)); }
### Question: BrokerEqualsPredicate implements FailedMessagePredicate { @Override public boolean test(FailedMessage failedMessage) { return broker.equals(failedMessage.getDestination().getBrokerName()); } BrokerEqualsPredicate(@JsonProperty("broker") String broker); @Override boolean test(FailedMessage failedMessage); @Override Description describe(Description description); @Override String toString(); }### Answer: @Test public void nameOfBrokerMatchers() { when(destination.getBrokerName()).thenReturn("some-broker"); assertThat(underTest.test(failedMessage), is(true)); } @Test public void nameOfBrokerDoesNotMatch() { when(destination.getBrokerName()).thenReturn("another-broker"); assertThat(underTest.test(failedMessage), is(false)); }
### Question: MongoStatusHistoryQueryBuilder { public Document currentStatusNotEqualTo(Status status) { return new Document(STATUS_HISTORY + ".0." + STATUS, new Document(NE, status.name())); } Document currentStatusEqualTo(Status status); Document currentStatusNotEqualTo(Status status); Document currentStatusIn(Set<Status> statuses); Document currentStatusIn(Document query, Set<Status> statuses); }### Answer: @Test public void currentStatusNotEqualTo() { assertThat(underTest.currentStatusNotEqualTo(DELETED), hasField(STATUS_HISTORY + ".0." + STATUS, hasField(NE, equalTo(DELETED.name())))); }
### Question: OrPredicate implements FailedMessagePredicate { @Override public boolean test(FailedMessage failedMessage) { return predicates .stream() .anyMatch(p -> p.test(failedMessage)); } OrPredicate(@JsonProperty("predicates") List<FailedMessagePredicate> predicates); @Override boolean test(FailedMessage failedMessage); List<FailedMessagePredicate> getPredicates(); @Override Description<T> describe(Description<T> description); @Override String toString(); }### Answer: @Test public void shortCutEvaluationWhenFirstPredicateIsTrue() { when(failedMessagePredicate1.test(failedMessage)).thenReturn(true); assertThat(underTest.test(failedMessage), is(true)); verify(failedMessagePredicate1).test(failedMessage); verifyZeroInteractions(failedMessagePredicate2); } @Test public void bothPredicatesAreEvaluatedWhenFirstPredicateReturnsFalse() { when(failedMessagePredicate1.test(failedMessage)).thenReturn(false); when(failedMessagePredicate2.test(failedMessage)).thenReturn(true); assertThat(underTest.test(failedMessage), is(true)); verify(failedMessagePredicate1).test(failedMessage); verify(failedMessagePredicate2).test(failedMessage); } @Test public void allPredicatesReturnFalse() { when(failedMessagePredicate1.test(failedMessage)).thenReturn(false); when(failedMessagePredicate2.test(failedMessage)).thenReturn(false); assertThat(underTest.test(failedMessage), is(false)); verify(failedMessagePredicate1).test(failedMessage); verify(failedMessagePredicate2).test(failedMessage); }
### Question: OrPredicate implements FailedMessagePredicate { public List<FailedMessagePredicate> getPredicates() { return predicates; } OrPredicate(@JsonProperty("predicates") List<FailedMessagePredicate> predicates); @Override boolean test(FailedMessage failedMessage); List<FailedMessagePredicate> getPredicates(); @Override Description<T> describe(Description<T> description); @Override String toString(); }### Answer: @Test public void canSerialiseAndDeserialisePredicate() throws IOException { ObjectMapper objectMapper = JacksonConfiguration.defaultObjectMapper(); objectMapper.registerSubtypes(BooleanPredicate.class); final OrPredicate underTest = objectMapper.readValue( objectMapper.writeValueAsString(new OrPredicate(singletonList(alwaysTruePredicate))), OrPredicate.class ); assertThat(underTest.getPredicates(), contains(alwaysTruePredicate)); }
### Question: OrPredicate implements FailedMessagePredicate { @Override public <T> Description<T> describe(Description<T> description) { Description<T> finalDescription = description.append("( "); final Iterator<FailedMessagePredicate> iterator = predicates.iterator(); while (iterator.hasNext()) { finalDescription = iterator.next().describe(finalDescription); if (iterator.hasNext()) { finalDescription = finalDescription.append(" OR "); } } return finalDescription.append(" )"); } OrPredicate(@JsonProperty("predicates") List<FailedMessagePredicate> predicates); @Override boolean test(FailedMessage failedMessage); List<FailedMessagePredicate> getPredicates(); @Override Description<T> describe(Description<T> description); @Override String toString(); }### Answer: @Test public void testDescribe() { when(failedMessagePredicate1.describe(any(StringDescription.class))).thenAnswer(withDescription("predicate1")); when(failedMessagePredicate2.describe(any(StringDescription.class))).thenAnswer(withDescription("predicate2")); assertThat(underTest.describe(new StringDescription()).getOutput(), is("( predicate1 OR predicate2 )")); }
### Question: OrPredicate implements FailedMessagePredicate { @Override public String toString() { return describe(new StringDescription()).toString(); } OrPredicate(@JsonProperty("predicates") List<FailedMessagePredicate> predicates); @Override boolean test(FailedMessage failedMessage); List<FailedMessagePredicate> getPredicates(); @Override Description<T> describe(Description<T> description); @Override String toString(); }### Answer: @Test public void toStringTest() { when(failedMessagePredicate1.describe(any(StringDescription.class))).thenAnswer(withDescription("predicate1")); when(failedMessagePredicate2.describe(any(StringDescription.class))).thenAnswer(withDescription("predicate2")); assertThat(underTest.toString(), is("( predicate1 OR predicate2 )")); }
### Question: DeleteMessageAction implements FailedMessageAction { @Override public void accept(FailedMessage failedMessage) { failedMessageService.delete(failedMessage.getFailedMessageId()); } DeleteMessageAction(@JacksonInject FailedMessageService failedMessageService); @Override void accept(FailedMessage failedMessage); @Override String toString(); }### Answer: @Test public void canSerialiseAndDeserialiseAction() throws Exception { DeleteMessageAction underTest = objectMapper.readValue( objectMapper.writeValueAsString(new DeleteMessageAction(failedMessageService)), DeleteMessageAction.class ); when(failedMessage.getFailedMessageId()).thenReturn(FAILED_MESSAGE_ID); underTest.accept(failedMessage); verify(failedMessageService).delete(FAILED_MESSAGE_ID); }
### Question: DeleteMessageAction implements FailedMessageAction { @Override public String toString() { return "delete failedMessage"; } DeleteMessageAction(@JacksonInject FailedMessageService failedMessageService); @Override void accept(FailedMessage failedMessage); @Override String toString(); }### Answer: @Test public void testToString() { assertThat(new DeleteMessageAction(failedMessageService).toString(), is("delete failedMessage")); }
### Question: LabelMessageAction implements FailedMessageAction { @Override public void accept(FailedMessage failedMessage) { failedMessageLabelService.addLabel(failedMessage.getFailedMessageId(), label); } LabelMessageAction(@JsonProperty("label") String label, @JacksonInject FailedMessageLabelService failedMessageLabelService); @Override void accept(FailedMessage failedMessage); @Override String toString(); }### Answer: @Test public void canSerialiseAndDeserialiseAction() throws Exception { LabelMessageAction underTest = objectMapper.readValue( objectMapper.writeValueAsString(new LabelMessageAction("foo", failedMessageLabelService)), LabelMessageAction.class ); when(failedMessage.getFailedMessageId()).thenReturn(FAILED_MESSAGE_ID); underTest.accept(failedMessage); verify(failedMessageLabelService).addLabel(FAILED_MESSAGE_ID, "foo"); }
### Question: LabelMessageAction implements FailedMessageAction { @Override public String toString() { return "set label '" + label + "'"; } LabelMessageAction(@JsonProperty("label") String label, @JacksonInject FailedMessageLabelService failedMessageLabelService); @Override void accept(FailedMessage failedMessage); @Override String toString(); }### Answer: @Test public void testToString() { LabelMessageAction underTest = new LabelMessageAction("foo", failedMessageLabelService); assertThat(underTest.toString(), Matchers.is("set label 'foo'")); }
### Question: FailedMessageMongoDao implements FailedMessageDao { @Override public Optional<FailedMessage> findById(FailedMessageId failedMessageId) { return Optional.ofNullable(collection .find(failedMessageConverter.createId(failedMessageId)) .map(failedMessageConverter::convertToObject) .first()); } FailedMessageMongoDao(MongoCollection<Document> collection, FailedMessageConverter failedMessageConverter, DocumentConverter<StatusHistoryEvent> failedMessageStatusConverter, RemoveRecordsQueryFactory removeRecordsQueryFactory); @Override void insert(FailedMessage failedMessage); @Override void update(FailedMessage failedMessage); @Override List<StatusHistoryEvent> getStatusHistory(FailedMessageId failedMessageId); @Override Optional<FailedMessage> findById(FailedMessageId failedMessageId); @Override long findNumberOfMessagesForBroker(String broker); @Override long removeFailedMessages(); @Override void addLabel(FailedMessageId failedMessageId, String label); @Override void setLabels(FailedMessageId failedMessageId, Set<String> labels); @Override void removeLabel(FailedMessageId failedMessageId, String label); }### Answer: @Test public void findFailedMessageThatDoesNotExistReturnsNull() { assertThat(underTest.findById(newFailedMessageId()), is(Optional.empty())); }
### Question: ResendFailedMessageAction implements FailedMessageAction { @Override public void accept(FailedMessage failedMessage) { failedMessageService.update( failedMessage.getFailedMessageId(), new StatusUpdateRequest(RESEND, clock.instant().plus(getResendDelay()))); } ResendFailedMessageAction(@JsonProperty("resendDelay") Duration resendDelay, @JacksonInject FailedMessageService failedMessageService); ResendFailedMessageAction(Duration resendDelay, FailedMessageService failedMessageService, Clock clock); @Override void accept(FailedMessage failedMessage); @Override String toString(); }### Answer: @Test public void resendFailedMessageActionWithNullDelay() { ResendFailedMessageAction underTest = resendFailedMessageActionWithFixedClock(null); underTest.accept(failedMessage); verify(failedMessageService).update(eq(FAILED_MESSAGE_ID), statusUpdateRequest.capture()); assertThat(statusUpdateRequest.getValue(), aStatusUpdateRequest(RESEND).withUpdatedDateTime(FIXED_CLOCK.instant())); } @Test public void resendFailedMessageActionWithGivenDelay() { ResendFailedMessageAction underTest = resendFailedMessageActionWithFixedClock(Duration.ofSeconds(10)); underTest.accept(failedMessage); verify(failedMessageService).update(eq(FAILED_MESSAGE_ID), statusUpdateRequest.capture()); assertThat(statusUpdateRequest.getValue(), aStatusUpdateRequest(RESEND).withUpdatedDateTime(FIXED_CLOCK.instant().plusSeconds(10))); }
### Question: ResendFailedMessageAction implements FailedMessageAction { @Override public String toString() { return "resend in " + formatDurationHMS(getResendDelay().toMillis()); } ResendFailedMessageAction(@JsonProperty("resendDelay") Duration resendDelay, @JacksonInject FailedMessageService failedMessageService); ResendFailedMessageAction(Duration resendDelay, FailedMessageService failedMessageService, Clock clock); @Override void accept(FailedMessage failedMessage); @Override String toString(); }### Answer: @Test public void testToString() { ResendFailedMessageAction underTest = resendFailedMessageActionWithFixedClock(Duration.ofDays(2).plusMinutes(15).plusSeconds(10).plusMillis(5)); assertThat(underTest.toString(), Matchers.is("resend in 48:15:10.005")); }
### Question: ChainedFailedMessageAction implements FailedMessageAction { @Override public void accept(FailedMessage failedMessage) { actions.forEach(action -> action.accept(failedMessage)); } ChainedFailedMessageAction(@JsonProperty("actions") List<FailedMessageAction> actions); @Override void accept(FailedMessage failedMessage); @Override String toString(); }### Answer: @Test public void allActionsInTheListAreExecuted() { ChainedFailedMessageAction underTest = new ChainedFailedMessageAction(Arrays.asList( failedMessageAction1, failedMessageAction2 )); underTest.accept(failedMessage); verify(failedMessageAction1).accept(failedMessage); verify(failedMessageAction2).accept(failedMessage); }
### Question: ChainedFailedMessageAction implements FailedMessageAction { @Override public String toString() { return actions.stream().map(Object::toString).collect(Collectors.joining(" AND ")); } ChainedFailedMessageAction(@JsonProperty("actions") List<FailedMessageAction> actions); @Override void accept(FailedMessage failedMessage); @Override String toString(); }### Answer: @Test public void testToString() { when(failedMessageAction1.toString()).thenReturn("action1"); when(failedMessageAction2.toString()).thenReturn("action2"); ChainedFailedMessageAction underTest = new ChainedFailedMessageAction(Arrays.asList( failedMessageAction1, failedMessageAction2 )); assertThat(underTest.toString(), Matchers.is("action1 AND action2")); }
### Question: MessageClassifierGroup implements MessageClassifier { @Override public MessageClassificationOutcome classify(MessageClassificationContext context) { MessageClassificationOutcome outcome = null; for (MessageClassifier messageClassifier : messageClassifiers) { final MessageClassificationOutcome latestOutcome = messageClassifier.classify(context); outcome = Optional.ofNullable(outcome).map(currentOutcome -> currentOutcome.or(latestOutcome)).orElse(latestOutcome); if (outcome.isMatched()) { return outcome; } } return Optional.ofNullable(outcome).orElse(context.notMatched(new BooleanPredicate(false))); } private MessageClassifierGroup(@JsonProperty("classifiers") List<MessageClassifier> messageClassifiers); static Builder newClassifierCollection(); static Builder copyClassifierCollection(MessageClassifierGroup messageClassifierGroup); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); List<MessageClassifier> getClassifiers(); }### Answer: @Test public void noClassifiersMatch() { when(messageClassifier1.classify(context)).thenReturn(classifier1Outcome); when(messageClassifier2.classify(context)).thenReturn(classifier2Outcome); when(classifier1Outcome.isMatched()).thenReturn(false); when(finalOutcome.isMatched()).thenReturn(false); when(classifier1Outcome.or(classifier2Outcome)).thenReturn(finalOutcome); assertThat(underTest.classify(context), is(finalOutcome)); verify(messageClassifier1).classify(context); verify(messageClassifier2).classify(context); verify(classifier1Outcome).or(classifier2Outcome); } @Test public void firstClassifierMatches() { when(messageClassifier1.classify(context)).thenReturn(classifier1Outcome); when(classifier1Outcome.isMatched()).thenReturn(true); assertThat(underTest.classify(context), is(this.classifier1Outcome)); verify(messageClassifier1).classify(context); verifyZeroInteractions(messageClassifier2); }
### Question: MessageClassifierGroup implements MessageClassifier { public static Builder newClassifierCollection() { return new Builder(); } private MessageClassifierGroup(@JsonProperty("classifiers") List<MessageClassifier> messageClassifiers); static Builder newClassifierCollection(); static Builder copyClassifierCollection(MessageClassifierGroup messageClassifierGroup); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); List<MessageClassifier> getClassifiers(); }### Answer: @Test public void canSerialiseAndDeserialiseMessageClassifier() throws IOException { final ObjectMapper objectMapper = JacksonConfiguration.defaultObjectMapper(); objectMapper.registerSubtypes(DoNothingMessageClassifier.class); underTest = newClassifierCollection() .withClassifier(new DoNothingMessageClassifier()) .withClassifier(new DoNothingMessageClassifier()) .build(); final String json = objectMapper.writeValueAsString(underTest); assertThat(json, allOf( hasJsonPath("$._classifier", equalTo("collection")), hasJsonPath("$.classifiers[0]._classifier", equalTo("doNothing")), hasJsonPath("$.classifiers[1]._classifier", equalTo("doNothing")) )); assertThat(objectMapper.readValue(json, MessageClassifier.class), reflectionEquals(underTest)); }
### Question: FailedMessageMongoDao implements FailedMessageDao { @Override public long findNumberOfMessagesForBroker(String broker) { return collection.count(new Document(DESTINATION + "." + BROKER_NAME, broker)); } FailedMessageMongoDao(MongoCollection<Document> collection, FailedMessageConverter failedMessageConverter, DocumentConverter<StatusHistoryEvent> failedMessageStatusConverter, RemoveRecordsQueryFactory removeRecordsQueryFactory); @Override void insert(FailedMessage failedMessage); @Override void update(FailedMessage failedMessage); @Override List<StatusHistoryEvent> getStatusHistory(FailedMessageId failedMessageId); @Override Optional<FailedMessage> findById(FailedMessageId failedMessageId); @Override long findNumberOfMessagesForBroker(String broker); @Override long removeFailedMessages(); @Override void addLabel(FailedMessageId failedMessageId, String label); @Override void setLabels(FailedMessageId failedMessageId, Set<String> labels); @Override void removeLabel(FailedMessageId failedMessageId, String label); }### Answer: @Test public void findNumberOfMessagesForBroker() { underTest.insert(failedMessageBuilder .withNewFailedMessageId() .withDestination(new Destination("brokerA", of("queue-name"))) .build()); underTest.insert(failedMessageBuilder .withNewFailedMessageId() .withDestination(new Destination("brokerB", of("queue-name"))) .build()); assertThat(underTest.findNumberOfMessagesForBroker("brokerA"), is(1L)); }
### Question: MessageClassifierGroup implements MessageClassifier { @Override public String toString() { return messageClassifiers.stream().map(MessageClassifier::toString).collect(Collectors.joining(" OR ")); } private MessageClassifierGroup(@JsonProperty("classifiers") List<MessageClassifier> messageClassifiers); static Builder newClassifierCollection(); static Builder copyClassifierCollection(MessageClassifierGroup messageClassifierGroup); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); List<MessageClassifier> getClassifiers(); }### Answer: @Test public void testToString() { when(messageClassifier1.toString()).thenReturn("classifier1"); when(messageClassifier2.toString()).thenReturn("classifier2"); final MessageClassifierGroup underTest = newClassifierCollection().withClassifier(messageClassifier1).withClassifier(messageClassifier2).build(); assertThat(underTest.toString(), is("classifier1 OR classifier2")); }
### Question: ExecutingMessageClassifier implements MessageClassifier { @Override public MessageClassificationOutcome classify(MessageClassificationContext context) { final boolean matched = predicate.test(context.getFailedMessage()); if (matched) { return context.matched(predicate, action); } else { return context.notMatched(predicate); } } ExecutingMessageClassifier(@JsonProperty("predicate") FailedMessagePredicate predicate, @JsonProperty("action") FailedMessageAction action); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); }### Answer: @Test public void actionIsExecutedIfThePredicateIsTrue() { when(context.getFailedMessage()).thenReturn(failedMessage); when(predicate.test(failedMessage)).thenReturn(true); when(context.matched(predicate, action)).thenReturn(outcome); assertThat(underTest.classify(context), is(outcome)); verify(predicate).test(failedMessage); verify(context).matched(predicate, action); } @Test public void actionIsNotExecutedIfThePredicateIsFalse() { when(context.getFailedMessage()).thenReturn(failedMessage); when(predicate.test(failedMessage)).thenReturn(false); when(context.notMatched(predicate)).thenReturn(outcome); assertThat(underTest.classify(context), is(outcome)); verify(predicate).test(failedMessage); verify(context).notMatched(predicate); }
### Question: ExecutingMessageClassifier implements MessageClassifier { @Override public String toString() { return "if " + predicate + " then " + action; } ExecutingMessageClassifier(@JsonProperty("predicate") FailedMessagePredicate predicate, @JsonProperty("action") FailedMessageAction action); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); }### Answer: @Test public void testToString() { when(predicate.toString()).thenReturn("predicate"); when(action.toString()).thenReturn("action"); assertThat(underTest.toString(), is("if predicate then action")); }
### Question: MessageClassificationOutcome { public String getDescription() { return predicate.describe(new StringDescription().append("matched = ").append(matched).append(", ")).getOutput(); } MessageClassificationOutcome(boolean matched, FailedMessagePredicate predicate, FailedMessage failedMessage, FailedMessageAction action); boolean isMatched(); String getDescription(); Description<T> getDescription(Description<T> description); FailedMessage getFailedMessage(); void execute(); @Override String toString(); MessageClassificationOutcome and(MessageClassificationOutcome outcome); MessageClassificationOutcome or(MessageClassificationOutcome outcome); }### Answer: @Test public void getDefaultDescription() { when(matchedPredicate.describe(any(StringDescription.class))).thenAnswer((Answer<Description<String>>) invocation -> ((StringDescription)invocation.getArgument(0)).append("predicate1")); assertThat(matched().getDescription(), is(equalTo("matched = true, predicate1"))); } @Test public void getDescription() { assertThat(matched().getDescription(description), is(notNullValue(Description.class))); }
### Question: DelegatingMessageClassifier implements MessageClassifier { @Override public MessageClassificationOutcome classify(MessageClassificationContext context) { final boolean matched = predicate.test(context.getFailedMessage()); if (matched) { return context.matched(predicate).and(messageClassifier.classify(context)); } else { return context.notMatched(predicate); } } DelegatingMessageClassifier(@JsonProperty("predicate") FailedMessagePredicate predicate, @JsonProperty("messageClassifier") MessageClassifier messageClassifier); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); }### Answer: @Test public void predicateIsNotMatched() { when(context.getFailedMessage()).thenReturn(failedMessage); when(predicate.test(failedMessage)).thenReturn(false); when(context.notMatched(predicate)).thenReturn(outcome); assertThat(underTest.classify(context), is(outcome)); verify(predicate).test(failedMessage); verify(context).notMatched(predicate); verifyZeroInteractions(messageClassifierGroup); } @Test public void predicateIsMatched() { when(context.getFailedMessage()).thenReturn(failedMessage); when(predicate.test(failedMessage)).thenReturn(true); MessageClassificationOutcome initialClassificationOutcome = mock(MessageClassificationOutcome.class); when(context.matched(predicate)).thenReturn(initialClassificationOutcome); MessageClassificationOutcome subsequentClassificationOutcome = mock(MessageClassificationOutcome.class); when(messageClassifierGroup.classify(context)).thenReturn(subsequentClassificationOutcome); when(initialClassificationOutcome.and(subsequentClassificationOutcome)).thenReturn(outcome); assertThat(underTest.classify(context), is(outcome)); verify(predicate).test(failedMessage); verify(context).matched(predicate); verify(initialClassificationOutcome).and(subsequentClassificationOutcome); }
### Question: DelegatingMessageClassifier implements MessageClassifier { @Override public String toString() { return "if " + predicate + " then " + messageClassifier; } DelegatingMessageClassifier(@JsonProperty("predicate") FailedMessagePredicate predicate, @JsonProperty("messageClassifier") MessageClassifier messageClassifier); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); }### Answer: @Test public void testToString() { when(predicate.toString()).thenReturn("predicate"); when(messageClassifierGroup.toString()).thenReturn("more classifiers"); assertThat(underTest.toString(), is("if predicate then more classifiers")); }
### Question: FailedMessagePredicateWithResult implements FailedMessagePredicate { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FailedMessagePredicateWithResult that = (FailedMessagePredicateWithResult) o; return result == that.result && Objects.equals(predicate, that.predicate); } FailedMessagePredicateWithResult(@JsonProperty("result") boolean result, @JsonProperty("predicate") FailedMessagePredicate predicate); @Override boolean test(FailedMessage failedMessage); @Override Description<T> describe(Description<T> description); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testEquals() { assertThat(underTest.equals(null), is(false)); assertThat(underTest.equals(new BooleanPredicate(true)), is(false)); assertThat(underTest.equals(new FailedMessagePredicateWithResult(false, failedMessagePredicate)), is(false)); assertThat(underTest.equals(new FailedMessagePredicateWithResult(true, mock(FailedMessagePredicate.class))), is(false)); assertThat(underTest.equals(new FailedMessagePredicateWithResult(true, failedMessagePredicate)), is(true)); }
### Question: FailedMessageMongoDao implements FailedMessageDao { @Override public long removeFailedMessages() { return collection.deleteMany(removeRecordsQueryFactory.create()).getDeletedCount(); } FailedMessageMongoDao(MongoCollection<Document> collection, FailedMessageConverter failedMessageConverter, DocumentConverter<StatusHistoryEvent> failedMessageStatusConverter, RemoveRecordsQueryFactory removeRecordsQueryFactory); @Override void insert(FailedMessage failedMessage); @Override void update(FailedMessage failedMessage); @Override List<StatusHistoryEvent> getStatusHistory(FailedMessageId failedMessageId); @Override Optional<FailedMessage> findById(FailedMessageId failedMessageId); @Override long findNumberOfMessagesForBroker(String broker); @Override long removeFailedMessages(); @Override void addLabel(FailedMessageId failedMessageId, String label); @Override void setLabels(FailedMessageId failedMessageId, Set<String> labels); @Override void removeLabel(FailedMessageId failedMessageId, String label); }### Answer: @Test public void removeOnAnEmptyCollection() { assertThat(underTest.removeFailedMessages(), is(0L)); }
### Question: FailedMessagePredicateWithResult implements FailedMessagePredicate { @Override public int hashCode() { return Objects.hash(result, predicate); } FailedMessagePredicateWithResult(@JsonProperty("result") boolean result, @JsonProperty("predicate") FailedMessagePredicate predicate); @Override boolean test(FailedMessage failedMessage); @Override Description<T> describe(Description<T> description); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testHashCode() { assertThat(underTest.hashCode(), is(Arrays.hashCode(new Object[] {true, failedMessagePredicate}))); }
### Question: MessageClassificationContext { public MessageClassificationOutcome notMatched(FailedMessagePredicate predicate) { return new MessageClassificationOutcome(false, new FailedMessagePredicateWithResult(false, predicate), failedMessage,null); } MessageClassificationContext(FailedMessage failedMessage); FailedMessage getFailedMessage(); MessageClassificationOutcome matched(FailedMessagePredicate predicate); MessageClassificationOutcome matched(FailedMessagePredicate predicate, FailedMessageAction action); MessageClassificationOutcome notMatched(FailedMessagePredicate predicate); @Override boolean equals(Object o); @Override int hashCode(); final FailedMessage failedMessage; }### Answer: @Test public void notMatched() { final MessageClassificationOutcome outcome = underTest.notMatched(failedMessagePredicate); assertThat(outcome.isMatched(), is(false)); assertThat(outcome.getFailedMessage(), is(failedMessage)); assertThat(outcome.getFailedMessageAction(), is(nullValue())); assertThat(outcome.getFailedMessagePredicate(), is(new FailedMessagePredicateWithResult(false, failedMessagePredicate))); }
### Question: UnmatchedMessageClassifier implements MessageClassifier { @Override public MessageClassificationOutcome classify(MessageClassificationContext context) { return context.notMatched(new BooleanPredicate(false)); } private UnmatchedMessageClassifier(); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final UnmatchedMessageClassifier ALWAYS_UNMATCHED; }### Answer: @Test public void testClassify() { when(context.getFailedMessage()).thenReturn(failedMessage); when(context.notMatched(new BooleanPredicate(false))).thenReturn(outcome); assertThat(underTest.classify(context), is(outcome)); }
### Question: UnmatchedMessageClassifier implements MessageClassifier { @Override public String toString() { return "unmatched"; } private UnmatchedMessageClassifier(); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final UnmatchedMessageClassifier ALWAYS_UNMATCHED; }### Answer: @Test public void testToString() { assertThat(underTest.toString(), is("unmatched")); }
### Question: UnmatchedMessageClassifier implements MessageClassifier { @Override public boolean equals(Object obj) { return this == obj; } private UnmatchedMessageClassifier(); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final UnmatchedMessageClassifier ALWAYS_UNMATCHED; }### Answer: @Test public void testEquals() { assertThat(underTest.equals(UnmatchedMessageClassifier.ALWAYS_UNMATCHED), is(true)); assertThat(underTest.equals(newClassifierCollection().build()), is(false)); assertThat(underTest.equals(null), is(false)); }
### Question: UnmatchedMessageClassifier implements MessageClassifier { @Override public int hashCode() { return 17 * 32; } private UnmatchedMessageClassifier(); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final UnmatchedMessageClassifier ALWAYS_UNMATCHED; }### Answer: @Test public void testHashCode() { assertThat(underTest.hashCode(), is(544)); }
### Question: MessageClassificationExecutorService { @ApiOperation( value = "Start the Message Classification executor with the configuration in application.yml", code = 204 ) @POST @Path("/start") public void start() { LOGGER.info("MessageClassificationService scheduled to start in {} {} and then execute every {} {}", initialDelay, timeUnit, executionFrequency, timeUnit ); scheduleAtAFixedRate(initialDelay); } MessageClassificationExecutorService(ScheduledExecutorService scheduledExecutorService, MessageClassificationService messageClassificationService, long initialDelay, long executionFrequency, TimeUnit timeUnit); @ApiOperation( value = "Start the Message Classification executor with the configuration in application.yml", code = 204 ) @POST @Path("/start") void start(); @ApiOperation( value = "Synchronously execute the resend job for the given broker", code = 204 ) @POST @Path("/execute") void execute(); @ApiOperation( value = "Pause/Stop the Message Classification executor", code = 204 ) @PUT @Path("/pause") void pause(); void stop(); }### Answer: @Test public void jobExecutesSuccessfully() throws Exception { underTest.start(); verifyMessageClassificationServiceExecutions(75); } @Test public void jobContinuesToExecuteIfExceptionIsThrown() throws InterruptedException { doAnswer(decrementCountdownLatchAndThrowException()) .when(messageClassificationService) .classifyFailedMessages(); underTest.start(); verifyMessageClassificationServiceExecutions(75); verifyMessageClassificationServiceExecutions(120); }
### Question: MessageClassificationExecutorService { public void stop() { LOGGER.info("Stopping execution of the MessageClassificationService"); scheduledExecutorService.shutdown(); LOGGER.info("Execution of the MessageClassificationService stopped"); } MessageClassificationExecutorService(ScheduledExecutorService scheduledExecutorService, MessageClassificationService messageClassificationService, long initialDelay, long executionFrequency, TimeUnit timeUnit); @ApiOperation( value = "Start the Message Classification executor with the configuration in application.yml", code = 204 ) @POST @Path("/start") void start(); @ApiOperation( value = "Synchronously execute the resend job for the given broker", code = 204 ) @POST @Path("/execute") void execute(); @ApiOperation( value = "Pause/Stop the Message Classification executor", code = 204 ) @PUT @Path("/pause") void pause(); void stop(); }### Answer: @Test public void executorCanBeStopped() { underTest.stop(); assertThat(scheduledExecutorService.isShutdown(), is(true)); }
### Question: MessageClassificationResource implements MessageClassificationClient { @Override public void addMessageClassifier(MessageClassifier messageClassifier) { messageClassificationRepository.save(MessageClassifierGroup.newClassifierCollection().withClassifier(messageClassifier).build()); } MessageClassificationResource(MessageClassificationRepository messageClassificationRepository, FailedMessageSearchService failedMessageSearchService, MessageClassificationOutcomeAdapter outcomeAdapter); @Override void addMessageClassifier(MessageClassifier messageClassifier); @Override MessageClassifier listAllMessageClassifiers(); @Override void removeAllMessageClassifiers(); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessageId failedMessageId); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessage failedMessage); }### Answer: @Test public void addMessageClassifierDelegatesToRepository() { ArgumentCaptor<MessageClassifierGroup> captor = ArgumentCaptor.forClass(MessageClassifierGroup.class); Mockito.doNothing().when(repository).save(captor.capture()); underTest.addMessageClassifier(messageClassifier); assertThat(captor.getValue().getClassifiers(), contains(messageClassifier)); verify(repository).save(captor.getValue()); }
### Question: FailedMessageMongoDao implements FailedMessageDao { @Override public void addLabel(FailedMessageId failedMessageId, String label) { UpdateResult updateResult = collection.updateOne( failedMessageConverter.createId(failedMessageId), new Document("$addToSet", new Document(LABELS, label)) ); LOGGER.debug("{} rows updated", updateResult.getModifiedCount()); } FailedMessageMongoDao(MongoCollection<Document> collection, FailedMessageConverter failedMessageConverter, DocumentConverter<StatusHistoryEvent> failedMessageStatusConverter, RemoveRecordsQueryFactory removeRecordsQueryFactory); @Override void insert(FailedMessage failedMessage); @Override void update(FailedMessage failedMessage); @Override List<StatusHistoryEvent> getStatusHistory(FailedMessageId failedMessageId); @Override Optional<FailedMessage> findById(FailedMessageId failedMessageId); @Override long findNumberOfMessagesForBroker(String broker); @Override long removeFailedMessages(); @Override void addLabel(FailedMessageId failedMessageId, String label); @Override void setLabels(FailedMessageId failedMessageId, Set<String> labels); @Override void removeLabel(FailedMessageId failedMessageId, String label); }### Answer: @Test public void addLabelToAFailedMessageThatDoesNotExist() { underTest.addLabel(failedMessageId, "foo"); assertThat(collection.count(), is(0L)); }
### Question: MessageClassificationResource implements MessageClassificationClient { @Override public MessageClassifier listAllMessageClassifiers() { return messageClassificationRepository.findLatest(); } MessageClassificationResource(MessageClassificationRepository messageClassificationRepository, FailedMessageSearchService failedMessageSearchService, MessageClassificationOutcomeAdapter outcomeAdapter); @Override void addMessageClassifier(MessageClassifier messageClassifier); @Override MessageClassifier listAllMessageClassifiers(); @Override void removeAllMessageClassifiers(); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessageId failedMessageId); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessage failedMessage); }### Answer: @Test public void listMessageClassifiers() { when(repository.findLatest()).thenReturn(messageClassifier); assertThat(underTest.listAllMessageClassifiers(), is(messageClassifier)); }
### Question: MessageClassificationResource implements MessageClassificationClient { @Override public void removeAllMessageClassifiers() { messageClassificationRepository.deleteAll(); } MessageClassificationResource(MessageClassificationRepository messageClassificationRepository, FailedMessageSearchService failedMessageSearchService, MessageClassificationOutcomeAdapter outcomeAdapter); @Override void addMessageClassifier(MessageClassifier messageClassifier); @Override MessageClassifier listAllMessageClassifiers(); @Override void removeAllMessageClassifiers(); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessageId failedMessageId); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessage failedMessage); }### Answer: @Test public void removeAllDelegatesFromRepository() { underTest.removeAllMessageClassifiers(); verify(repository).deleteAll(); }
### Question: InMemoryMessageClassificationRepository implements MessageClassificationRepository { @Override public void deleteAll() { messageClassifiers.add(UnmatchedMessageClassifier.ALWAYS_UNMATCHED); } InMemoryMessageClassificationRepository(); InMemoryMessageClassificationRepository(Vector<MessageClassifier> messageClassifiers); @Override void save(MessageClassifier messageClassifier); @Override MessageClassifier findLatest(); @Override void deleteAll(); }### Answer: @Test public void deleteAllMessageClassifiers() { messageClassifiers.add(messageClassifier); underTest.deleteAll(); assertThat(messageClassifiers, contains(messageClassifier, ALWAYS_UNMATCHED)); }
### Question: InMemoryMessageClassificationRepository implements MessageClassificationRepository { @Override public MessageClassifier findLatest() { return messageClassifiers.isEmpty() ? null : messageClassifiers.lastElement(); } InMemoryMessageClassificationRepository(); InMemoryMessageClassificationRepository(Vector<MessageClassifier> messageClassifiers); @Override void save(MessageClassifier messageClassifier); @Override MessageClassifier findLatest(); @Override void deleteAll(); }### Answer: @Test public void findLatestMessageClassifiers() { messageClassifiers.add(mock(MessageClassifier.class)); messageClassifiers.add(messageClassifier); final MessageClassifier messageClassifiers = underTest.findLatest(); assertThat(messageClassifiers, is(messageClassifier)); } @Test public void findLatestMessageClassifierWhenEmpty() { assertThat(new InMemoryMessageClassificationRepository().findLatest(), nullValue()); }
### Question: FailedMessageMongoDao implements FailedMessageDao { @Override public void removeLabel(FailedMessageId failedMessageId, String label) { collection.updateOne( failedMessageConverter.createId(failedMessageId), new Document("$pull", new Document(LABELS, label)) ); } FailedMessageMongoDao(MongoCollection<Document> collection, FailedMessageConverter failedMessageConverter, DocumentConverter<StatusHistoryEvent> failedMessageStatusConverter, RemoveRecordsQueryFactory removeRecordsQueryFactory); @Override void insert(FailedMessage failedMessage); @Override void update(FailedMessage failedMessage); @Override List<StatusHistoryEvent> getStatusHistory(FailedMessageId failedMessageId); @Override Optional<FailedMessage> findById(FailedMessageId failedMessageId); @Override long findNumberOfMessagesForBroker(String broker); @Override long removeFailedMessages(); @Override void addLabel(FailedMessageId failedMessageId, String label); @Override void setLabels(FailedMessageId failedMessageId, Set<String> labels); @Override void removeLabel(FailedMessageId failedMessageId, String label); }### Answer: @Test public void removeLabelForAFailedMessageThatDoesNotExist() { underTest.removeLabel(failedMessageId, "bar"); assertThat(collection.count(), is(0L)); }
### Question: PingServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { responseWriter.write(resp.getWriter()); } catch (IOException e) { handleError(resp, e); } } PingServlet(PingResponseWriter responseWriter); }### Answer: @Test public void successfullyWriteAResponse() throws Exception { when(httpServletResponse.getWriter()).thenReturn(printWriter); underTest.doGet(httpServletRequest, httpServletResponse); verify(responseWriter).write(printWriter); verifyZeroInteractions(httpServletRequest); } @Test public void unableToWriteAResponse() throws IOException, ServletException { when(httpServletResponse.getWriter()).thenThrow(IOException.class); underTest.doGet(httpServletRequest, httpServletResponse); verify(httpServletResponse).sendError(500, "An error occurred writing the response"); verifyZeroInteractions(responseWriter); verifyZeroInteractions(httpServletRequest); }
### Question: FailedMessageNotFoundException extends RuntimeException { public static Supplier<FailedMessageNotFoundException> failedMessageNotFound(FailedMessageId failedMessageId) { return () -> new FailedMessageNotFoundException(failedMessageId); } FailedMessageNotFoundException(FailedMessageId failedMessageId); static Supplier<FailedMessageNotFoundException> failedMessageNotFound(FailedMessageId failedMessageId); }### Answer: @Test public void verifySupplier() { final FailedMessageNotFoundException underTest = FailedMessageNotFoundException.failedMessageNotFound(FAILED_MESSAGE_ID).get(); assertEquals("Failed Message: " + FAILED_MESSAGE_ID + " not found", underTest.getMessage()); assertEquals("Failed Message: " + FAILED_MESSAGE_ID + " not found", underTest.getLocalizedMessage()); assertNull(underTest.getCause()); }
### Question: FailedMessageResponseFactory { public FailedMessageResponse create(FailedMessage failedMessage) { return new FailedMessageResponse( failedMessage.getFailedMessageId(), failedMessage.getDestination().getBrokerName(), failedMessage.getDestination().getName(), failedMessage.getSentAt(), failedMessage.getFailedAt(), failedMessage.getContent(), FailedMessageStatusAdapter.toFailedMessageStatus(failedMessage.getStatusHistoryEvent().getStatus()), failedMessage.getProperties(), failedMessage.getLabels()); } FailedMessageResponse create(FailedMessage failedMessage); }### Answer: @Test public void createFailedMessageResponseFromAFailedMessage() { FailedMessageResponse failedMessageResponse = underTest.create(newFailedMessage() .withContent("Hello World") .withDestination(new Destination("broker", of("queue"))) .withFailedDateTime(NOW) .withFailedMessageId(FAILED_MESSAGE_ID) .withProperties(Collections.singletonMap("foo", "bar")) .withSentDateTime(NOW) .build() ); assertThat(failedMessageResponse, CoreMatchers.is(aFailedMessage() .withFailedMessageId(equalTo(FAILED_MESSAGE_ID)) .withContent(equalTo("Hello World")) .withBroker(equalTo("broker")) .withDestination(equalTo(of("queue"))) .withFailedAt(equalTo(NOW)) .withProperties(Matchers.hasEntry("foo", "bar")) .withSentAt(equalTo(NOW)))); }
### Question: StatusUpdateRequestAdapter implements UpdateRequestAdapter<StatusUpdateRequest> { @Override public void adapt(StatusUpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder) { failedMessageBuilder.withStatusHistoryEvent(new StatusHistoryEvent(updateRequest.getStatus(), updateRequest.getEffectiveDateTime())); } @Override void adapt(StatusUpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder); }### Answer: @Test public void statusHistoryEventIsSet() { underTest.adapt(new StatusUpdateRequest(FAILED, NOW), failedMessageBuilder); verify(failedMessageBuilder).withStatusHistoryEvent( argThat(new HamcrestArgumentMatcher<>(StatusHistoryEventMatcher.equalTo(FAILED).withUpdatedDateTime(NOW))) ); }
### Question: LoggingUpdateRequestAdapter implements UpdateRequestAdapter<UpdateRequest> { @Override public void adapt(UpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder) { getLogger().warn("UpdateRequestAdapter not found for: {}", updateRequest.getClass().getName()); } @Override void adapt(UpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder); }### Answer: @Test public void classNameIsLoggedByTheAdapter() { underTest.adapt(new ExampleUpdateRequest(), failedMessageBuilder); verify(logger).warn("UpdateRequestAdapter not found for: {}", ExampleUpdateRequest.class.getName()); }