I will write a more detailed post about JUnit later on. But this is a good start to find out testing replacing occurrence in Java 🙂
Assuming the utility method is as follows:
public class Strings {
public static String replaceOccurence(String str, String search, String replace) {
StringBuffer buffer = new StringBuffer(str);
for (int i = 0; i < str.length() - search.length() + 1; i++) {
if (str.substring(i, i + search.length()).equals(search)) {
buffer.replace(i, i + search.length(), replace);
}
}
return buffer.toString();
}
}
In the following codeblock, the last method would be a good start to check:
public class TestStringManipulation extends TestCase {
public void testReplaceOnce() {
String input = "aaa bbb ccc";
String expected = "ddd bbb ccc";
String output = Strings.replaceOccurence(input, "aaa", "ddd");
assertEquals(expected, output);
}
public void testReplaceTwice() {
String input = "aaa bbb ccc aaa";
String expected = "ddd bbb ccc ddd";
String output = Strings.replaceOccurence(input, "aaa", "ddd");
assertEquals(expected, output);
}
public void testReplaceMultiple() {
String input = "ab ab ac ad ab ac ad ab ab ad";
String expected = "ba ba ac ad ba ac ad ba ba ad";
String output = Strings.replaceOccurence(input, "ab", "ba");
assertEquals(expected, output);
}
public void testMatchNotFound() {
String input = "ab ab ac ad ab ac ad ab ab ad";
String expected = "ab ab ac ad ab ac ad ab ab ad";
String output = Strings.replaceOccurence(input, "zz", "ba");
assertEquals(expected, output);
}
public void testReplaceSingleCharWithMultiChar() {
String input = "abcdefgabcdefgabcdefg";
String expected = "abcdefghijkabcdefghijkabcdefghijk";
String output = Strings.replaceOccurence(input, "g", "ghijk");
assertEquals(expected, output);
}
}