Skip to content

Instantly share code, notes, and snippets.

View unclebob's full-sized avatar

Robert C. Martin unclebob

View GitHub Profile
public class Wrapper {
public static String wrap(String s, int col) {
if (s.length() <= col)
return s;
else {
StringBuilder builder = new StringBuilder();
String[] strings = s.split(" ");
int column = 0;
for (String segment : strings) {
column += segment.length();
@Test
public void wrapWellBeforeWordBoundary() throws Exception {
assertThat(wrap("word word", 3), equalTo("wor\nd\nwor\nd"));
}
@RunWith(Suite.class)
@Suite.SuiteClasses({
WrapperTest.DegenerateTests.class,
WrapperTest.wrapWordsTest.class
})
public class WrapperTest {
public static class DegenerateTests {
@Test
public void emptyString() throws Exception {
@Test
public void wrapThreeWordsAfterSecondSpace() throws Exception {
assertThat(wrap("word word word", 11), equalTo("word word\nword"));
}
public class Wrapper {
public static String wrap(String s, int col) {
if (s.length() <= col)
return s;
else {
int lastSpace = 0;
int space;
while ((space = s.indexOf(" ", lastSpace)) != -1) {
if (space > col) {
s = s.substring(0, lastSpace) + "\n" + s.substring(lastSpace+1);
public static class DegenerateTests {
@Test
public void wrap_EmptyString_ShouldBeEmpty() throws Exception {
assertThat(wrap("", 1), equalTo(""));
}
@Test
public void stringShorterThanColDoesNotWrap() throws Exception {
assertThat(wrap("word", 10), equalTo("word"));
}
public static class SplitWordTests {
@Test
public void splitOneWord() throws Exception {
assertThat(wrap("word", 2), equalTo("wo\nrd"));
}
}
@Test
public void splitOneWordManyTimes() throws Exception {
assertThat(wrap("abcdefghij", 3), equalTo("abc\ndef\nghi\nj"));
}
public class Wrapper {
public static String wrap(String s, int col) {
if (s.length() <= col)
return s;
else
return (s.substring(0, col) + "\n" + wrap(s.substring(col), col));
}
}
public static class WrapTwoWords {
@Test
public void wrapOnWordBoundary() throws Exception {
assertThat(wrap("word word", 5), equalTo("word\nword"));
}
}