-
Notifications
You must be signed in to change notification settings - Fork 0
CompareNames Test case
I created a test case that checks the functionality of the CompareNames.closeEnough(str1, str2) method.
This should return true if the two strings in the parameter are "close enough" to each other. This is useful to filter out typos from the input. Here is the code of the tested methods:
public static boolean closeEnough(String str1, String str2) {
//completely random threshold to see if two strings are similar
if (str1.equals(str2))
return true;
String s1 = convertString(str1);
String s2 = convertString(str2);
boolean result;
result = compare(s1, s2);
if (!result)
result = compare(s2, s1);
return result;
}
The convertString function removes the following delimiters from the string: { '_', '-', ' ', '(', ')', '.' }. After that, the compare function checks the two strings:
private static boolean compare(String s1, String s2) {
int endIndex = (int) Math.round(s1.length() * THRESHOLD);
if(endIndex < 0 && endIndex < s1.length()) {
return false;
}
String part1 = s1.substring(0, endIndex);
if (part1.length() <= TOO_SMALL)
return false;
else if ((s2.indexOf(part1) != -1 && ((float) s1.length()) / ((float) s2.length()) > THRESHOLD))
return true;
else if (Math.abs(s1.length() - s2.length()) > TOO_SMALL)
return false;
else {
int f;
for (f = 0; f < s1.length() && f < s2.length(); f++) {
if (s1.charAt(f) != s2.charAt(f))
break;
}
if (f == s1.length() || f == s2.length())
return false; // **should never get here actually;
int b;
for (b = 1; b < s1.length() && b < s2.length(); b++) {
if (s1.charAt(s1.length() - b) != s2.charAt(s2.length() - b))
break;
}
if (Math.abs((s1.length() - b) - f) < TYPO_LENGTH)
return true;
}
return false;
}
The term "close enough" is true, if the two strings are identical or only differ in two characters. To check that I created the following test case:
public void testCompareNames(){
String str1 = "Compare";
String str2 = "Compare";
assertTrue(CompareNames.closeEnough(str1, str2));
str1 = "Comparx";
str2 = "Compare";
assertTrue(CompareNames.closeEnough(str1, str2));
str1 = "Compaxx";
str2 = "Compare";
assertTrue(CompareNames.closeEnough(str1, str2));
str1 = "Compxxx";
str2 = "Compare";
assertFalse(CompareNames.closeEnough(str1, str2));
}
Before every assert I assign values to the string variables. In the first three cases it should return true:
- at first the two strings are the same
- at the second one only the last character is different
- at the third one the last two characters are different.
In the last case, the last three characters are not the same, so the are not "close enough" to each other, it is not considered as a typo.