### Question:
JavaCode extends Code { public String methodBody(String method) { StringBuilder result = new StringBuilder(); int depth = 0; for (String line : this) { String trimmedLine = line.trim(); if (depth > 0) { if ("}".equals(trimmedLine) && --depth == 0) { break; } else { if (result.length() > 0) { result.append('\n'); } result.append(trimmedLine); if (trimmedLine.endsWith("{")) { depth++; } } } Matcher methodMatcher = METHOD_NAME_PATTERN.matcher(trimmedLine); if (methodMatcher.matches() && method.equals(methodMatcher.group(4))) { depth = 1; } } return result.toString(); } JavaCode(); String typeName(); boolean isClass(); Collection<String> typeAnnotations(); Collection<String> imports(); Collection<String> methods(); Collection<String> methodAnnotations(String method); String methodReturns(String method); String methodArguments(String method); String packageName(); String fullyQualifiedName(); String methodBody(String method); Collection<String> fieldNames(); String fieldType(String fieldName); Iterable<String> fieldAnnotations(String fieldName); String fieldValue(String fieldName); Iterable<String> fileComments(); String superTypeName(); Iterable<String> implementedInterfaces(); boolean isType(String type); boolean fieldIsContant(String fieldName); Iterable<String> fieldComments(String fieldName); String constructorBody(); void ensureImport(String packageName, String typeName); String simpleTypeName(); static final String TYPE_PATTERN; static final String NAME_PATTERN; }### Answer:
@Test public void extractsMethodBody() { String singleLineMethod = "m1" + someValue(); String singleLine = "return 42;"; String complexMethod = "m2" + someValue(); Code complexBody = new Code(); complexBody.add("if (false) {"); complexBody.add("return 666;"); complexBody.add("}"); complexBody.add("return 313;"); String complexText = complexBody.text().trim(); code.add("public class C {"); code.add(" public int %s() {", singleLineMethod); code.add(" %s", singleLine); code.add(" }"); code.add(" public int %s() {", complexMethod); for (String line : complexBody) { code.add(" %s", line); } code.add(" }"); code.add("}"); assertEquals("Single line body", singleLine, code.methodBody(singleLineMethod)); assertEquals("Empty body", "", code.methodBody(someValue())); assertEquals("Complex body", complexText, code.methodBody(complexMethod)); }