method2testcases
stringlengths
118
3.08k
### Question: StringUtil extends UtilityClass { public static String camelToUpper(String camelName) { if (StringUtils.isEmpty(camelName)) { return ""; } return Arrays.stream(camelName.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) .filter(StringUtils::isNotBlank) .map(String::toUpperCase) .collect(joining("_")); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }### Answer: @ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @NullValue("<NULL>") @TestCase({"<NULL>", ""}) @TestCase({"", ""}) @TestCase({"a", "A"}) @TestCase({"B", "B"}) @TestCase({"abc", "ABC"}) @TestCase({" def", " DEF"}) @TestCase({"aBC", "A_BC"}) @TestCase({"camelCase", "CAMEL_CASE"}) @TestCase({"camelCaseWithTLA", "CAMEL_CASE_WITH_TLA"}) @TestCase({"camelCaseWithTLAInMiddle", "CAMEL_CASE_WITH_TLA_IN_MIDDLE"}) @TestCase({"tlaAtStart", "TLA_AT_START"}) @TestCase({"NotCamelCase", "NOT_CAMEL_CASE"}) @TestCase({"TLANotCamelCase", "TLA_NOT_CAMEL_CASE"}) void camelToUpper(String input, String expectedResult) { assertThat(StringUtil.camelToUpper(input), is(expectedResult)); }
### Question: SelectStatement { From from() { return from; } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void from() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); From result = sut.from(); assertThat(result, sameInstance(from)); }
### Question: StringUtil extends UtilityClass { public static String hex(byte... bytes) { if (bytes == null) { return ""; } StringBuilder builder = new StringBuilder(bytes.length * 2); for (byte b : bytes) { builder.append(String.format("%02x", b)); } return builder.toString(); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }### Answer: @ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", ""}) @TestCase({"", ""}) @TestCase({"-128", "80"}) @TestCase({"-1", "ff"}) @TestCase({"0", "00"}) @TestCase({"15", "0f"}) @TestCase({"127", "7f"}) @TestCase({"0, 127, 10", "007f0a"}) @TestCase({"0xde,0xad,0xbe,0xef", "deadbeef"}) void hex(byte[] input, String expectedResult) { assertThat(StringUtil.hex(input), is(expectedResult)); }
### Question: StringUtil extends UtilityClass { public static String octal(byte... bytes) { if (bytes == null) { return ""; } StringBuilder builder = new StringBuilder(bytes.length * 3); for (byte b : bytes) { builder.append(String.format("%03o", b)); } return builder.toString(); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }### Answer: @ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", ""}) @TestCase({"", ""}) @TestCase({"-128", "200"}) @TestCase({"-1", "377"}) @TestCase({"0", "000"}) @TestCase({"15", "017"}) @TestCase({"127", "177"}) @TestCase({"0, 127, 10", "000177012"}) void octal(byte[] input, String expectedResult) { assertThat(StringUtil.octal(input), is(expectedResult)); }
### Question: StringUtil extends UtilityClass { public static <T> Function<T,String> prepend(String arg) { return s -> coalesce(arg, "") + coalesce(s, ""); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }### Answer: @ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"", "null", ""}) @TestCase({"", "", ""}) @TestCase({"null", "", ""}) @TestCase({"null", "null", ""}) @TestCase({"null", "A", "A"}) @TestCase({"", "A", "A"}) @TestCase({"A", "", "A"}) @TestCase({"A", "null", "A"}) @TestCase({"null", "xyz", "xyz"}) @TestCase({"", "xyz", "xyz"}) @TestCase({"z", "xy", "xyz"}) @TestCase({"yz", "x", "xyz"}) @TestCase({"xyz", "", "xyz"}) @TestCase({"xyz", "null", "xyz"}) void prepend(String input, String prefix, String expectedOutput) { String result = StringUtil.prepend(prefix).apply(input); assertThat(result, is(expectedOutput)); }
### Question: StringUtil extends UtilityClass { public static <T> Function<T,String> append(String arg) { return s -> coalesce(s, "") + coalesce(arg, ""); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }### Answer: @ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"", "null", ""}) @TestCase({"", "", ""}) @TestCase({"null", "", ""}) @TestCase({"null", "null", ""}) @TestCase({"null", "A", "A"}) @TestCase({"", "A", "A"}) @TestCase({"A", "", "A"}) @TestCase({"A", "null", "A"}) @TestCase({"null", "xyz", "xyz"}) @TestCase({"", "xyz", "xyz"}) @TestCase({"x", "yz", "xyz"}) @TestCase({"xy", "z", "xyz"}) @TestCase({"xyz", "", "xyz"}) @TestCase({"xyz", "null", "xyz"}) void append(String input, String suffix, String expectedOutput) { String result = StringUtil.append(suffix).apply(input); assertThat(result, is(expectedOutput)); }
### Question: FieldUtil extends UtilityClass { public static void set(Field field, Object target, Object value) { field.setAccessible(true); try { field.set(target, value); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } static void set(Field field, Object target, Object value); static Object get(Field field, Object target); static Object get(String fieldName, Object target); static Optional<Class<?>> genericTypeArgument(Field field, int index); static boolean hasAnnotation(Class<? extends Annotation> annotationClass, Field field); static Optional<A> annotation(Class<A> annotationClass, Field field); }### Answer: @Test void set() { ClassWithStringField target = new ClassWithStringField(); String value = UUID.randomUUID().toString(); Field field = ClassUtil.getDeclaredField(ClassWithStringField.class, "stringField"); FieldUtil.set(field, target, value); assertThat(target.getStringField(), equalTo(value)); }
### Question: FieldUtil extends UtilityClass { public static Object get(Field field, Object target) { field.setAccessible(true); try { return field.get(target); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } static void set(Field field, Object target, Object value); static Object get(Field field, Object target); static Object get(String fieldName, Object target); static Optional<Class<?>> genericTypeArgument(Field field, int index); static boolean hasAnnotation(Class<? extends Annotation> annotationClass, Field field); static Optional<A> annotation(Class<A> annotationClass, Field field); }### Answer: @Test void get() { ClassWithStringField target = new ClassWithStringField(); String value = UUID.randomUUID().toString(); target.setStringField(value); Field field = ClassUtil.getDeclaredField(ClassWithStringField.class, "stringField"); Object result = FieldUtil.get(field, target); assertThat(result, equalTo(value)); } @Test void getFromObjectSuccess() { ClassWithStringField target = new ClassWithStringField(); String value = UUID.randomUUID().toString(); target.setStringField(value); Object result = FieldUtil.get("stringField", target); assertThat(result, equalTo(value)); } @Test void getFromObjectError() { ClassWithStringField target = new ClassWithStringField(); calling(() -> FieldUtil.get("rubbish", target)) .shouldThrow(IllegalArgumentException.class) .withMessage(is("No such field as rubbish in class com.cadenzauk.core.reflect.util.FieldUtilTest$ClassWithStringField")); }
### Question: SelectStatement { Scope scope() { return scope; } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void scope() { Scope scope = createScope(); SelectStatement<Integer> sut = new SelectStatement<>(scope, TypeToken.of(Integer.class), from, rowMapper, projection); Scope result = sut.scope(); assertThat(result, sameInstance(scope)); }
### Question: FieldUtil extends UtilityClass { public static Optional<Class<?>> genericTypeArgument(Field field, int index) { return genericType(field) .map(gt -> TypeUtil.actualTypeArgument(gt, index)); } static void set(Field field, Object target, Object value); static Object get(Field field, Object target); static Object get(String fieldName, Object target); static Optional<Class<?>> genericTypeArgument(Field field, int index); static boolean hasAnnotation(Class<? extends Annotation> annotationClass, Field field); static Optional<A> annotation(Class<A> annotationClass, Field field); }### Answer: @Test void genericTypeArgumentSuccess() { Optional<Class<?>> result = FieldUtil.genericTypeArgument(ClassUtil.getDeclaredField(ClassWithStringField.class, "optionalStringField"), 0); assertThat(result, is(Optional.of(String.class))); } @Test void genericTypeArgumentNotGeneric() { Optional<Class<?>> result = FieldUtil.genericTypeArgument(ClassUtil.getDeclaredField(ClassWithStringField.class, "stringField"), 0); assertThat(result, is(Optional.empty())); } @Test void genericTypeArgumentInvalidIndex() { calling(() -> FieldUtil.genericTypeArgument(ClassUtil.getDeclaredField(ClassWithStringField.class, "optionalStringField"), 1)) .shouldThrow(ArrayIndexOutOfBoundsException.class); }
### Question: FieldUtil extends UtilityClass { public static boolean hasAnnotation(Class<? extends Annotation> annotationClass, Field field) { return field.getAnnotation(annotationClass) != null; } static void set(Field field, Object target, Object value); static Object get(Field field, Object target); static Object get(String fieldName, Object target); static Optional<Class<?>> genericTypeArgument(Field field, int index); static boolean hasAnnotation(Class<? extends Annotation> annotationClass, Field field); static Optional<A> annotation(Class<A> annotationClass, Field field); }### Answer: @Test void hasAnnotationPresent() { Field field = ClassUtil.getDeclaredField(ClassWithStringField.class, "stringField"); boolean result = FieldUtil.hasAnnotation(XmlElement.class, field); assertThat(result, is(true)); } @Test void hasAnnotationNotPresent() { Field field = ClassUtil.getDeclaredField(ClassWithStringField.class, "stringField"); boolean result = FieldUtil.hasAnnotation(XmlAttribute.class, field); assertThat(result, is(false)); }
### Question: FieldUtil extends UtilityClass { public static <A extends Annotation> Optional<A> annotation(Class<A> annotationClass, Field field) { return Optional.ofNullable(field.getAnnotation(annotationClass)); } static void set(Field field, Object target, Object value); static Object get(Field field, Object target); static Object get(String fieldName, Object target); static Optional<Class<?>> genericTypeArgument(Field field, int index); static boolean hasAnnotation(Class<? extends Annotation> annotationClass, Field field); static Optional<A> annotation(Class<A> annotationClass, Field field); }### Answer: @Test void annotationPresent() { Field field = ClassUtil.getDeclaredField(ClassWithStringField.class, "stringField"); Optional<XmlElement> result = FieldUtil.annotation(XmlElement.class, field); assertThat(result.isPresent(), is(true)); } @Test void annotationNotPresent() { Field field = ClassUtil.getDeclaredField(ClassWithStringField.class, "stringField"); Optional<XmlAttribute> result = FieldUtil.annotation(XmlAttribute.class, field); assertThat(result, is(Optional.empty())); }
### Question: MethodUtil extends UtilityClass { public static Object invoke(Method method, Object target, Object... args) { try { method.setAccessible(true); return method.invoke(target, args); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } static Object invoke(Method method, Object target, Object... args); static Stream<A> annotations(Class<A> annotationClass, Method method); static Method fromReference(Function1<T,V> methodReference); static Method fromReference(FunctionInt<T> methodReference); static Method fromReference(FunctionOptional1<T,V> methodReference); static Class<?> referringClass(Function1<T,V> methodReference); static Class<?> referringClass(FunctionInt<T> methodReference); static Class<?> referringClass(FunctionOptional1<T,V> methodReference); }### Answer: @Test void invokeNoArgsVoid() throws NoSuchMethodException { TestClass mock = Mockito.mock(TestClass.class); Method method1 = mock.getClass().getDeclaredMethod("method1"); MethodUtil.invoke(method1, mock); Mockito.verify(mock, times(1)).method1(); } @Test void invokeThrowsException() throws NoSuchMethodException { TestClass mock = Mockito.mock(TestClass.class); doThrow(IllegalFormatCodePointException.class).when(mock).method1(); Method method1 = mock.getClass().getDeclaredMethod("method1"); calling(() -> MethodUtil.invoke(method1, mock)) .shouldThrow(RuntimeException.class) .withCause(InvocationTargetException.class) .withCause(IllegalFormatCodePointException.class); Mockito.verify(mock, times(1)).method1(); } @Test void invokeNoArgsWithResult() throws NoSuchMethodException { TestClass mock = Mockito.mock(TestClass.class); Optional<String> expectedResult = Optional.of("The result"); when(mock.method2()).thenReturn(expectedResult); Method method2 = mock.getClass().getDeclaredMethod("method2"); Object result = MethodUtil.invoke(method2, mock); Mockito.verify(mock, times(1)).method2(); assertThat(result, is(expectedResult)); }
### Question: SelectStatement { String sql(Scope outerScope) { return "(" + sqlImpl(outerScope) + ")"; } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void sql() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); when(projection.sql(any())).thenReturn("*"); when(from.sql(any())).thenReturn(" from foo"); when(booleanExpression1.sql(any())).thenReturn("1 = 2"); when(booleanExpression1.precedence()).thenReturn(Precedence.COMPARISON); sut.setWhereClause(booleanExpression1); sut.addGroupBy(TypedExpression.literal("ABC")); sut.addOrderBy(1, Order.DESC); String result = sut.sql(); assertThat(result, is("select * from foo where 1 = 2 group by 'ABC' order by 1 desc")); }
### Question: MethodUtil extends UtilityClass { public static <T, V> Method fromReference(Function1<T,V> methodReference) { return OptionalUtil.orGet(fromJavaFunction(methodReference), () -> fromKotlinFunction(methodReference)) .orElseThrow(() -> new RuntimeException("Failed to find writeReplace method in " + methodReference.getClass())); } static Object invoke(Method method, Object target, Object... args); static Stream<A> annotations(Class<A> annotationClass, Method method); static Method fromReference(Function1<T,V> methodReference); static Method fromReference(FunctionInt<T> methodReference); static Method fromReference(FunctionOptional1<T,V> methodReference); static Class<?> referringClass(Function1<T,V> methodReference); static Class<?> referringClass(FunctionInt<T> methodReference); static Class<?> referringClass(FunctionOptional1<T,V> methodReference); }### Answer: @Test void fromReference() { Method method = MethodUtil.fromReference(TestDerivedClass::derivedMethod); assertThat(method.getName(), is("derivedMethod")); assertThat(method.getDeclaringClass().getCanonicalName(), is(TestDerivedClass.class.getCanonicalName())); } @Test void fromReferenceToOptionalMethodWithoutClass() { Method method = MethodUtil.fromReference(TestClass::method2); assertThat(method.getName(), is("method2")); assertThat(method.getDeclaringClass().getCanonicalName(), is(TestClass.class.getCanonicalName())); } @Test void fromReferenceToBaseOptionalMethodWithoutClass() { Method method = MethodUtil.fromReference(TestDerivedClass::method2); assertThat(method.getName(), is("method2")); assertThat(method.getDeclaringClass().getCanonicalName(), is(TestClass.class.getCanonicalName())); } @Test void fromReferenceToBaseOptionalMethodGivenDerivedClass() { Method method = MethodUtil.fromReference(TestClass::method2); assertThat(method.getName(), is("method2")); assertThat(method.getDeclaringClass().getCanonicalName(), is(TestClass.class.getCanonicalName())); }
### Question: SelectStatement { RowMapper<RT> rowMapper() { return rowMapper; } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void rowMapper() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); RowMapper<Integer> result = sut.rowMapper(); assertThat(result, sameInstance(rowMapper)); }
### Question: ClassUtil extends UtilityClass { @SuppressWarnings("unchecked") public static <T> Class<T> forObject(T value) { Objects.requireNonNull(value); return (Class<T>) value.getClass(); } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void forObject() { Class<Number> numberClass = ClassUtil.forObject(BigDecimal.ONE); assertThat(numberClass, equalTo(BigDecimal.class)); }
### Question: ClassUtil extends UtilityClass { public static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes) { try { return Optional.of(aClass.getDeclaredMethod(name, parameterTypes)); } catch (NoSuchMethodException e) { return Optional.empty(); } } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void declaredMethodForMethodThatExistsIsTheMethod() { Optional<Method> method0 = ClassUtil.declaredMethod(TestingTarget.class, "method"); assertThat(method0.isPresent(), is(true)); assertThat(method0.map(Method::getName), is(Optional.of("method"))); } @Test void declaredMethodForMethodWithWrongParametersIsEmpty() { Optional<Method> method0 = ClassUtil.declaredMethod(TestingTarget.class, "method", Integer.class); assertThat(method0, is(Optional.empty())); }
### Question: ClassUtil extends UtilityClass { public static Optional<Class<?>> forName(String className) { try { return Optional.of(Class.forName(className)); } catch (ClassNotFoundException e) { return Optional.empty(); } } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void forNameOfClassThatExists() { Optional<Class<?>> result = ClassUtil.forName(TestingTarget.class.getName()); assertThat(result, is(Optional.of(TestingTarget.class))); } @Test void forNameOfNonClassIsEmpty() { Optional<Class<?>> result = ClassUtil.forName("com.dodgy.nothing.to.see.here.Bob"); assertThat(result, is(Optional.empty())); }
### Question: ClassUtil extends UtilityClass { public static Optional<Class<?>> forArrayOf(Class<?> componentClass) { return OptionalUtil.orGet( TypeUtil.findPrimitiveArrayType(componentClass), () -> forName("[L" + componentClass.getCanonicalName() + ";")); } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void forArrayOfPrimitive() { Optional<Class<?>> result = ClassUtil.forArrayOf(Double.TYPE); assertThat(result, is(Optional.of(double[].class))); } @Test void forArrayOfGeneric() { Optional<Class<?>> result = ClassUtil.forArrayOf(List.class); assertThat(result, is(Optional.of(List[].class))); }
### Question: ClassUtil extends UtilityClass { public static Field getDeclaredField(Class<?> aClass, String fieldName) { return declaredField(aClass, fieldName) .orElseThrow(() -> new NoSuchElementException("No such field as " + fieldName + " in " + aClass)); } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void getDeclaredFieldPresentIsReturned() { Field result = ClassUtil.getDeclaredField(TestingTarget.class, "stringField"); assertThat(result, notNullValue()); assertThat(result.getName(), equalTo("stringField")); } @Test void getDeclaredFieldNotPresentThrows() { calling(() -> ClassUtil.getDeclaredField(TestingTarget.class, "nothingToSeeHere")) .shouldThrow(NoSuchElementException.class) .withMessage(is("No such field as nothingToSeeHere in class com.cadenzauk.core.reflect.util.ClassUtilTest$TestingTarget")); }
### Question: SelectStatement { InWhereExpectingAnd<RT> setWhereClause(BooleanExpression e) { whereClause.start(e); return new InWhereExpectingAnd<>(this); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void setWhereClause() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); when(projection.sql(any())).thenReturn("*"); when(from.sql(any())).thenReturn(" from foo"); when(booleanExpression1.sql(any())).thenReturn("a = b"); when(booleanExpression1.precedence()).thenReturn(Precedence.COMPARISON); sut.setWhereClause(booleanExpression1); assertThat(sut.sql(), is("select * from foo where a = b")); }
### Question: ClassUtil extends UtilityClass { public static Optional<Field> declaredField(Class<?> aClass, String fieldName) { try { return Optional.of(aClass.getDeclaredField(fieldName)); } catch (NoSuchFieldException e) { return Optional.empty(); } } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void declaredFieldPresentIsReturned() { Optional<Field> result = ClassUtil.declaredField(TestingTarget.class, "stringField"); assertThat(result.isPresent(), equalTo(true)); assertThat(result.map(Field::getName), equalTo(Optional.of("stringField"))); } @Test void declaredFieldNotPresentIsEmpty() { Optional<Field> result = ClassUtil.declaredField(TestingTarget.class, "nothingToSeeHere"); assertThat(result, is(Optional.empty())); }
### Question: ClassUtil extends UtilityClass { public static Optional<Field> findField(Class<?> aClass, String fieldName) { return superclasses(aClass) .map(cls -> declaredField(cls, fieldName)) .flatMap(StreamUtil::of) .findFirst(); } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void findFieldInTargetFound() { Optional<Field> result = ClassUtil.findField(TestingTarget.class, "stringField"); assertThat(result.isPresent(), is(true)); assertThat(result.map(Field::getName), is(Optional.of("stringField"))); } @Test void findFieldInBaseFound() { Optional<Field> result = ClassUtil.findField(TestingTarget.class, "baseField"); assertThat(result.isPresent(), is(true)); assertThat(result.map(Field::getName), is(Optional.of("baseField"))); } @Test void findFieldNotFound() { Optional<Field> result = ClassUtil.findField(TestingTarget.class, "yesWeHaveNoBananas"); assertThat(result, is(Optional.empty())); }
### Question: ClassUtil extends UtilityClass { public static Optional<Class<?>> superclass(Class<?> aClass) { return Optional.ofNullable(aClass.getSuperclass()); } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void superclassOfNonObjectIsPresent() { Optional<Class<?>> result = ClassUtil.superclass(TestingTargetBase.class); assertThat(result, is(Optional.of(Object.class))); } @Test void superclassOfObjectIsEmpty() { Optional<Class<?>> result = ClassUtil.superclass(Object.class); assertThat(result, is(Optional.empty())); } @Test void superclassOfInterfaceIsEmpty() { Optional<Class<?>> result = ClassUtil.superclass(TestingInterface.class); assertThat(result, is(Optional.empty())); }
### Question: SelectStatement { void andWhere(BooleanExpression e) { whereClause.appendAnd(e); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void andWhere() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); when(projection.sql(any())).thenReturn("*"); when(from.sql(any())).thenReturn(" from foo"); when(booleanExpression1.sql(any())).thenReturn("a = b"); when(booleanExpression1.precedence()).thenReturn(Precedence.COMPARISON); when(booleanExpression2.sql(any())).thenReturn("c = d"); when(booleanExpression2.precedence()).thenReturn(Precedence.COMPARISON); sut.setWhereClause(booleanExpression1); sut.andWhere(booleanExpression2); assertThat(sut.sql(), is("select * from foo where a = b and c = d")); }
### Question: ClassUtil extends UtilityClass { public static <A extends Annotation> boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass) { return aClass.getAnnotation(annotationClass) != null; } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void hasAnnotationThatIsPresent() { boolean result = ClassUtil.hasAnnotation(TestingTarget.class, XmlRootElement.class); assertThat(result, is(true)); } @Test void hasAnnotationThatIsNotPresent() { boolean result = ClassUtil.hasAnnotation(TestingTargetBase.class, XmlRootElement.class); assertThat(result, is(false)); }
### Question: ClassUtil extends UtilityClass { public static <A extends Annotation, T> Optional<A> annotation(Class<T> aClass, Class<A> annotationClass) { return Optional.ofNullable(aClass.getAnnotation(annotationClass)); } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void annotationThatIsPresent() { Optional<XmlRootElement> result = ClassUtil.annotation(TestingTarget.class, XmlRootElement.class); assertThat(result.isPresent(), is(true)); } @Test void annotationThatIsNotPresent() { Optional<XmlRootElement> result = ClassUtil.annotation(TestingTargetBase.class, XmlRootElement.class); assertThat(result, is(Optional.empty())); }
### Question: ClassUtil extends UtilityClass { public static <T> Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes) { try { return Optional.of(aClass.getDeclaredConstructor(parameterTypes)); } catch (NoSuchMethodException e) { return Optional.empty(); } } @SuppressWarnings("unchecked") static Class<T> forObject(T value); static Optional<Class<?>> forName(String className); static Optional<Class<?>> forArrayOf(Class<?> componentClass); static Method getDeclaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Optional<Method> declaredMethod(Class<?> aClass, String name, Class<?>... parameterTypes); static Stream<Method> declaredMethods(Class<?> aClass); static Field getDeclaredField(Class<?> aClass, String fieldName); static Optional<Field> declaredField(Class<?> aClass, String fieldName); static Optional<Field> findField(Class<?> aClass, String fieldName); static Optional<Class<?>> superclass(Class<?> aClass); static Stream<Class<?>> superclasses(Class<?> aClass); static boolean hasAnnotation(Class<?> aClass, Class<A> annotationClass); static Optional<A> annotation(Class<T> aClass, Class<A> annotationClass); static Stream<A> annotations(Class<T> aClass, Class<A> annotationClass); static Optional<Constructor<T>> constructor(Class<T> aClass, Class<?>... parameterTypes); }### Answer: @Test void defaultConstructorPresent() { Optional<Constructor<TestingTargetBase>> result = ClassUtil.constructor(TestingTargetBase.class); assertThat(result.isPresent(), is(true)); } @Test void defaultConstructorNotPresent() { Optional<Constructor<TestingTarget>> result = ClassUtil.constructor(TestingTarget.class); assertThat(result, is(Optional.empty())); } @Test void constructorWithArgsPresent() { Optional<Constructor<TestingTarget>> result = ClassUtil.constructor(TestingTarget.class, String.class); assertThat(result.isPresent(), is(true)); }
### Question: SelectStatement { void orWhere(BooleanExpression e) { whereClause.appendOr(e); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void orWhere() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); when(projection.sql(any())).thenReturn("*"); when(from.sql(any())).thenReturn(" from foo"); when(booleanExpression1.sql(any())).thenReturn("a = b"); when(booleanExpression1.precedence()).thenReturn(Precedence.COMPARISON); when(booleanExpression2.sql(any())).thenReturn("c = d"); when(booleanExpression2.precedence()).thenReturn(Precedence.COMPARISON); sut.setWhereClause(booleanExpression1); sut.orWhere(booleanExpression2); assertThat(sut.sql(), is("select * from foo where a = b or c = d")); }
### Question: TypeUtil extends UtilityClass { @SuppressWarnings({"SuspiciousMethodCalls"}) public static Class<?> primitiveComponentType(Type primitiveArrayType) { return Optional.ofNullable(ARRAY_TO_PRIMITIVE.get(primitiveArrayType)) .orElseThrow(() -> new IllegalArgumentException(toString(primitiveArrayType) + " is not a primative array.")); } @SuppressWarnings("unchecked") static Class<V> boxedType(Class<V> primitiveType); @SuppressWarnings("unchecked") static TypeToken<V> boxedType(TypeToken<V> primitiveType); @SuppressWarnings({"SuspiciousMethodCalls"}) static Class<?> primitiveComponentType(Type primitiveArrayType); static Optional<Class<?>> findPrimitiveArrayType(Type primitiveComponentType); static Class<?> actualTypeArgument(ParameterizedType parameterizedType, int i); static String toString(Type type); }### Answer: @Test void primitiveComponentOfNonPrimitiveThrows() { calling(() -> TypeUtil.primitiveComponentType(Byte[].class)) .shouldThrow(IllegalArgumentException.class) .withMessage("Byte[] is not a primative array."); }
### Question: SelectStatement { InHavingExpectingAnd<RT> setHavingClause(BooleanExpression e) { havingClause.start(e); return new InHavingExpectingAnd<>(this); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void setHavingClause() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); when(projection.sql(any())).thenReturn("*"); when(from.sql(any())).thenReturn(" from foo"); when(booleanExpression1.sql(any())).thenReturn("a = b"); when(booleanExpression1.precedence()).thenReturn(Precedence.COMPARISON); sut.setHavingClause(booleanExpression1); assertThat(sut.sql(), is("select * from foo having a = b")); }
### Question: Getter extends UtilityClass { public static boolean isGetter(Method method, Field forField) { return getMethods().anyMatch(g -> StringUtils.equals(g.apply(forField.getName()), method.getName())); } @NotNull static Function<T,Optional<V>> forField(Class<T> targetClass, Class<V> argType, Field field); @NotNull static FunctionOptional1<T,V> forField(TypeToken<T> targetType, Class<V> argType, Field field); static boolean isGetter(Method method, Field forField); static Stream<String> possibleFieldNames(String name); }### Answer: @Test void isGetter() { assertThat(Getter.isGetter( fromReference(GetterTestClass::fieldWithUnprefixedGetter), getDeclaredField(GetterTestClass.class, "fieldWithUnprefixedGetter")), is(true)); assertThat(Getter.isGetter( fromReference(GetterTestClass::getFieldWithGetPrefixedGetter), getDeclaredField(GetterTestClass.class, "fieldWithGetPrefixedGetter")), is(true)); assertThat(Getter.isGetter( fromReference(GetterTestClass::optionalFieldWithUnprefixedGetter), getDeclaredField(GetterTestClass.class, "optionalFieldWithUnprefixedGetter")), is(true)); assertThat(Getter.isGetter( fromReference(GetterTestClass::getOptionalFieldWithGetPrefixedGetter), getDeclaredField(GetterTestClass.class, "optionalFieldWithGetPrefixedGetter")), is(true)); assertThat(Getter.isGetter( fromReference(GetterTestClass::isFieldWithIsPrefixedGetter), getDeclaredField(GetterTestClass.class, "fieldWithIsPrefixedGetter")), is(true)); assertThat(Getter.isGetter( fromReference(GetterTestClass::isOptionalFieldWithIsPrefixedGetter), getDeclaredField(GetterTestClass.class, "optionalFieldWithIsPrefixedGetter")), is(true)); }
### Question: SelectStatement { void andHaving(BooleanExpression e) { havingClause.appendAnd(e); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void andHaving() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); when(projection.sql(any())).thenReturn("*"); when(from.sql(any())).thenReturn(" from foo"); when(booleanExpression1.sql(any())).thenReturn("a = b"); when(booleanExpression1.precedence()).thenReturn(Precedence.COMPARISON); when(booleanExpression2.sql(any())).thenReturn("c = d"); when(booleanExpression2.precedence()).thenReturn(Precedence.COMPARISON); sut.setHavingClause(booleanExpression1); sut.andHaving(booleanExpression2); assertThat(sut.sql(), is("select * from foo having a = b and c = d")); }
### Question: SelectStatement { public TypeToken<RT> rowType() { return rowType; } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void rowType() { TypeToken<Integer> typeToken = TypeToken.of(Integer.class); SelectStatement<Integer> sut = new SelectStatement<>(createScope(), typeToken, from, rowMapper, projection); TypeToken<Integer> result = sut.rowType(); assertThat(result, is(typeToken)); }
### Question: FieldInfo { @SuppressWarnings("unchecked") public static <R> FieldInfo<R,?> of(Class<R> declaringClass, Field field) { if (field.getType() == Optional.class) { return genericTypeArgument(field, 0) .map(cls -> of(declaringClass, field, cls)) .orElseThrow(() -> new IllegalArgumentException("Unable to determine the type of Optional field " + field.getName() + " in " + declaringClass)); } return of(declaringClass, field, field.getType()); } private FieldInfo(TypeToken<C> declaringType, Field field, Class<F> effectiveType); @Override String toString(); TypeToken<C> declaringType(); @SuppressWarnings("unchecked") Class<C> declaringClass(); Field field(); String name(); Class<?> fieldType(); Class<F> effectiveClass(); TypeToken<F> effectiveType(); FunctionOptional1<C, F> optionalGetter(); boolean hasAnnotation(Class<A> annotation); Optional<A> annotation(Class<A> annotation); @SuppressWarnings("unchecked") static FieldInfo<R,?> of(Class<R> declaringClass, Field field); @SuppressWarnings("unchecked") static FieldInfo<R,?> of(TypeToken<R> declaringClass, Field field); static FieldInfo<R,T> of(Class<R> rowClass, Field field, Class<T> fieldType); static FieldInfo<R,T> of(TypeToken<R> rowClass, Field field, Class<T> fieldType); static FieldInfo<C,F> of(Class<C> objectClass, String fieldName, Class<F> fieldType); static Optional<FieldInfo<C,F>> ofGetter(MethodInfo<C,F> getter); }### Answer: @Test void ofWrongTypeThrowsException() { calling(() -> FieldInfo.of(ClassWithField.class, "string", Integer.class)) .shouldThrow(NoSuchElementException.class) .withMessage(is("No field called string of type class java.lang.Integer in class com.cadenzauk.core.reflect.FieldInfoTest$ClassWithField")); }
### Question: Factory extends UtilityClass { public static <T> Supplier<T> forClass(Class<T> aClass) { return ClassUtil.constructor(aClass) .map(Factory::invoke) .orElseGet(() -> () -> ObjenesisHelper.newInstance(aClass)); } static Supplier<T> forClass(Class<T> aClass); @SuppressWarnings("unchecked") static Supplier<T> forType(TypeToken<T> aClass); }### Answer: @Test void cannotInstantiate() { calling(() -> Factory.forClass(Factory.class).get()) .shouldThrow(RuntimeException.class) .withMessage(is("java.lang.reflect.InvocationTargetException")) .withCause(InvocationTargetException.class) .withCause(RuntimeInstantiationException.class); } @Test void forClassOnClassWithDefaultConstructor() { Supplier<ClassWithMultipleConstructors> factory = Factory.forClass(ClassWithMultipleConstructors.class); ClassWithMultipleConstructors result = factory.get(); assertThat(result, notNullValue()); assertThat(result.intValue(), is(501)); } @Test void forClassOnClassWithNoDefaultConstructor() { Supplier<NoDefaultConstructor> noDefaultConstructorSupplier = Factory.forClass(NoDefaultConstructor.class); NoDefaultConstructor noDefaultConstructor = noDefaultConstructorSupplier.get(); assertThat(noDefaultConstructor, notNullValue()); assertThat(noDefaultConstructor, instanceOf(NoDefaultConstructor.class)); }
### Question: SelectStatement { void orHaving(BooleanExpression e) { havingClause.appendOr(e); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void orHaving() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); when(projection.sql(any())).thenReturn("*"); when(from.sql(any())).thenReturn(" from foo"); when(booleanExpression1.sql(any())).thenReturn("a = b"); when(booleanExpression1.precedence()).thenReturn(Precedence.COMPARISON); when(booleanExpression2.sql(any())).thenReturn("c = d"); when(booleanExpression2.precedence()).thenReturn(Precedence.COMPARISON); sut.setHavingClause(booleanExpression1); sut.orHaving(booleanExpression2); assertThat(sut.sql(), is("select * from foo having a = b or c = d")); }
### Question: TypeInfo { @Override public String toString() { return TypeUtil.toString(type); } private TypeInfo(Type type); @Override String toString(); TypeInfo arrayComponentType(); TypeInfo actualTypeArgument(int index); Class<?> rawClass(); static TypeInfo ofParameter(Method method, int parameter); }### Answer: @ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({OPTIONAL_PARAMETER + "", "Optional<String>"}) @TestCase({INT_PARAMETER + "", "int"}) @TestCase({ZONED_DATE_TIME_PARAMETER + "", "ZonedDateTime"}) @TestCase({LIST_ARRAY_PARAMETER + "", "List<Optional<UUID>>[]"}) @TestCase({FLOAT_ARRAY_PARAMETER + "", "float[]"}) @TestCase({MAP_PARAMETER + "", "Map<Short,BigDecimal>"}) void toStringTest(int arg, String expected) { TypeInfo sut = TypeInfo.ofParameter(randomMethod(), arg); String result = sut.toString(); assertThat(result, equalTo(expected)); }
### Question: TypeInfo { public static TypeInfo ofParameter(Method method, int parameter) { return new TypeInfo(method.getGenericParameterTypes()[parameter]); } private TypeInfo(Type type); @Override String toString(); TypeInfo arrayComponentType(); TypeInfo actualTypeArgument(int index); Class<?> rawClass(); static TypeInfo ofParameter(Method method, int parameter); }### Answer: @Test void arrayComponentTypeThrowsIfNotArray() { TypeInfo sut = TypeInfo.ofParameter(randomMethod(), MAP_PARAMETER); calling(sut::arrayComponentType) .shouldThrow(NoSuchElementException.class) .withMessage("Map<Short,BigDecimal> is not an array type."); } @Test void ofParameter() { Method randomMethod = randomMethod(); TypeInfo result = TypeInfo.ofParameter(randomMethod, OPTIONAL_PARAMETER); assertThat(result.rawClass(), equalTo(Optional.class)); assertThat(result.actualTypeArgument(0).rawClass(), equalTo(String.class)); }
### Question: TypeInfo { public TypeInfo actualTypeArgument(int index) { return new TypeInfo(parameterizedType .map(p -> typeArg(p, index)) .orElseThrow(() -> new NoSuchElementException(TypeUtil.toString(type) + " is not a parameterized type so does not have actual type arguments."))); } private TypeInfo(Type type); @Override String toString(); TypeInfo arrayComponentType(); TypeInfo actualTypeArgument(int index); Class<?> rawClass(); static TypeInfo ofParameter(Method method, int parameter); }### Answer: @Test void actualTypeArgument() { TypeInfo sut = TypeInfo.ofParameter(randomMethod(), OPTIONAL_PARAMETER); TypeInfo result = sut.actualTypeArgument(0); assertThat(result.rawClass(), equalTo(String.class)); }
### Question: TypeInfo { public Class<?> rawClass() { return parameterizedType .map(ParameterizedType::getRawType) .map(Class.class::cast) .orElseGet(() -> genericArrayType .flatMap(x -> ClassUtil.forArrayOf(of(x.getGenericComponentType()).rawClass())) .orElseGet(() -> (Class) type)); } private TypeInfo(Type type); @Override String toString(); TypeInfo arrayComponentType(); TypeInfo actualTypeArgument(int index); Class<?> rawClass(); static TypeInfo ofParameter(Method method, int parameter); }### Answer: @Test void rawClass() { TypeInfo sut = TypeInfo.ofParameter(randomMethod(), ZONED_DATE_TIME_PARAMETER); Class<?> result = sut.rawClass(); assertThat(result, equalTo(ZonedDateTime.class)); }
### Question: ResultSetUtil extends UtilityClass { public static String getString(ResultSet rs, String columnLabel) { try { return rs.getString(columnLabel); } catch (SQLException e) { throw new RuntimeSqlException(e); } } static String getString(ResultSet rs, String columnLabel); static void close(ResultSet rs); static Stream<T> stream(ResultSet rs, RowMapper<T> rowMapper); static Stream<T> stream(ThrowingSupplier<ResultSet, ? extends SQLException> rs, RowMapper<T> rowMapper); }### Answer: @Test void getString() throws SQLException { String column = RandomStringUtils.randomAlphabetic(10); String expectedValue = RandomStringUtils.random(40); when(resultSet.getString(column)).thenReturn(expectedValue); String result = ResultSetUtil.getString(resultSet, column); assertThat(result, is(expectedValue)); verify(resultSet, times(1)).getString(column); verifyNoMoreInteractions(resultSet); }
### Question: ResultSetUtil extends UtilityClass { public static void close(ResultSet rs) { try { rs.close(); } catch (SQLException e) { throw new RuntimeSqlException(e); } } static String getString(ResultSet rs, String columnLabel); static void close(ResultSet rs); static Stream<T> stream(ResultSet rs, RowMapper<T> rowMapper); static Stream<T> stream(ThrowingSupplier<ResultSet, ? extends SQLException> rs, RowMapper<T> rowMapper); }### Answer: @Test void close() throws SQLException { ResultSetUtil.close(resultSet); verify(resultSet, times(1)).close(); verifyNoMoreInteractions(resultSet); }
### Question: ResultSetUtil extends UtilityClass { public static <T> Stream<T> stream(ResultSet rs, RowMapper<T> rowMapper) { CompositeAutoCloseable closer = new CompositeAutoCloseable(); closer.add(rs); return StreamSupport.stream(new ResultSetSpliterator<>(rs, rowMapper, closer::close), false).onClose(closer::close); } static String getString(ResultSet rs, String columnLabel); static void close(ResultSet rs); static Stream<T> stream(ResultSet rs, RowMapper<T> rowMapper); static Stream<T> stream(ThrowingSupplier<ResultSet, ? extends SQLException> rs, RowMapper<T> rowMapper); }### Answer: @ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase("true") @TestCase("false") void stream(boolean close) throws SQLException { int count = RandomUtils.nextInt(5, 10); String[] mappedRows = Stream.generate(() -> RandomStringUtils.randomAlphabetic(30)).limit(count).toArray(String[]::new); MockUtil.when(rowMapper.mapRow(resultSet)).thenReturn(mappedRows); MockUtil.when(resultSet.next()).thenReturn(count, true).thenReturn(false); Stream<String> result = ResultSetUtil.stream(resultSet, rowMapper); List<String> items = result.collect(toList()); if (close) { result.close(); } assertThat(items, contains(mappedRows)); verify(resultSet, times(count + 1)).next(); verify(rowMapper, times(count)).mapRow(resultSet); verify(resultSet, times(1)).close(); verifyNoMoreInteractions(resultSet, rowMapper); }
### Question: DataSourceUtil extends UtilityClass { public static Connection connection(DataSource dataSource) { try { return dataSource.getConnection(); } catch (SQLException e) { throw new RuntimeSqlException(e); } } static Connection connection(DataSource dataSource); }### Answer: @Test void connection() throws SQLException { when(dataSource.getConnection()).thenReturn(expected); Connection connection = DataSourceUtil.connection(dataSource); verify(dataSource).getConnection(); verifyNoMoreInteractions(dataSource); assertThat(connection, sameInstance(expected)); } @Test void connectionThatThrows() throws SQLException { when(dataSource.getConnection()).thenThrow(new SQLException("We have none")); calling(() -> DataSourceUtil.connection(dataSource)) .shouldThrow(RuntimeSqlException.class) .withCause(SQLException.class) .withMessage(is("We have none")); verify(dataSource).getConnection(); verifyNoMoreInteractions(dataSource); }
### Question: PreparedStatementUtil extends UtilityClass { public static void setObject(PreparedStatement preparedStatement, int i, Object arg) { try { preparedStatement.setObject(i, arg); } catch (SQLException e) { throw new RuntimeSqlException(e); } } static void setObject(PreparedStatement preparedStatement, int i, Object arg); static int executeUpdate(PreparedStatement preparedStatement); static boolean execute(PreparedStatement preparedStatement); static ResultSet executeQuery(PreparedStatement preparedStatement); }### Answer: @Test void setObject() throws SQLException { PreparedStatementUtil.setObject(preparedStatement, 3, "Foo"); verify(preparedStatement).setObject(3, "Foo"); verifyNoMoreInteractions(preparedStatement); } @Test void setObjectThatThrows() throws SQLException { doThrow(new SQLException("Bad param")).when(preparedStatement).setObject(anyInt(), any()); calling(() -> PreparedStatementUtil.setObject(preparedStatement, 3, "Foo")) .shouldThrow(RuntimeSqlException.class) .withCause(SQLException.class) .withMessage(is("Bad param")); verify(preparedStatement).setObject(3, "Foo"); verifyNoMoreInteractions(preparedStatement); }
### Question: PreparedStatementUtil extends UtilityClass { public static int executeUpdate(PreparedStatement preparedStatement) { try { return preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeSqlException(e); } } static void setObject(PreparedStatement preparedStatement, int i, Object arg); static int executeUpdate(PreparedStatement preparedStatement); static boolean execute(PreparedStatement preparedStatement); static ResultSet executeQuery(PreparedStatement preparedStatement); }### Answer: @Test void executeUpdate() throws SQLException { when(preparedStatement.executeUpdate()).thenReturn(121); int result = PreparedStatementUtil.executeUpdate(preparedStatement); verify(preparedStatement).executeUpdate(); verifyNoMoreInteractions(preparedStatement); assertThat(result, is(121)); } @Test void executeUpdateThatThrows() throws SQLException { when(preparedStatement.executeUpdate()).thenThrow(new SQLException("Update failed")); calling(() -> PreparedStatementUtil.executeUpdate(preparedStatement)) .shouldThrow(RuntimeSqlException.class) .withCause(SQLException.class) .withMessage(is("Update failed")); verify(preparedStatement).executeUpdate(); verifyNoMoreInteractions(preparedStatement); }
### Question: ConnectionUtil extends UtilityClass { public static DatabaseMetaData getMetaData(Connection connection) { try { return connection.getMetaData(); } catch (SQLException e) { throw new RuntimeSqlException(e); } } static DatabaseMetaData getMetaData(Connection connection); static void commit(Connection connection); static void rollback(Connection connection); static boolean execute(Connection connection, String sql); static PreparedStatement prepare(Connection connection, String sql); }### Answer: @Test void getMetaData() throws SQLException { when(connection.getMetaData()).thenReturn(metadata); DatabaseMetaData result = ConnectionUtil.getMetaData(connection); verify(connection).getMetaData(); verifyNoMoreInteractions(connection); assertThat(result, sameInstance(metadata)); } @Test void getMetaDataThatThrows() throws SQLException { String message = RandomStringUtils.randomAlphabetic(50); when(connection.getMetaData()).thenThrow(new SQLException(message)); calling(() -> ConnectionUtil.getMetaData(connection)) .shouldThrow(RuntimeSqlException.class) .withCause(SQLException.class) .withMessage(is(message)); verify(connection).getMetaData(); verifyNoMoreInteractions(connection); }
### Question: ConnectionUtil extends UtilityClass { public static void commit(Connection connection) { try { connection.commit(); } catch (SQLException e) { throw new RuntimeSqlException(e); } } static DatabaseMetaData getMetaData(Connection connection); static void commit(Connection connection); static void rollback(Connection connection); static boolean execute(Connection connection, String sql); static PreparedStatement prepare(Connection connection, String sql); }### Answer: @Test void commit() throws SQLException { ConnectionUtil.commit(connection); verify(connection).commit(); verifyNoMoreInteractions(connection); } @Test void commitThatThrows() throws SQLException { String message = RandomStringUtils.randomAlphabetic(50); doThrow(new SQLException(message)).when(connection).commit(); calling(() -> ConnectionUtil.commit(connection)) .shouldThrow(RuntimeSqlException.class) .withCause(SQLException.class) .withMessage(is(message)); verify(connection).commit(); verifyNoMoreInteractions(connection); }
### Question: ConnectionUtil extends UtilityClass { public static void rollback(Connection connection) { try { connection.rollback(); } catch (SQLException e) { throw new RuntimeSqlException(e); } } static DatabaseMetaData getMetaData(Connection connection); static void commit(Connection connection); static void rollback(Connection connection); static boolean execute(Connection connection, String sql); static PreparedStatement prepare(Connection connection, String sql); }### Answer: @Test void rollback() throws SQLException { ConnectionUtil.rollback(connection); verify(connection).rollback(); verifyNoMoreInteractions(connection); } @Test void rollbackThatThrows() throws SQLException { String message = RandomStringUtils.randomAlphabetic(50); doThrow(new SQLException(message)).when(connection).rollback(); calling(() -> ConnectionUtil.rollback(connection)) .shouldThrow(RuntimeSqlException.class) .withCause(SQLException.class) .withMessage(is(message)); verify(connection).rollback(); verifyNoMoreInteractions(connection); }
### Question: ConnectionUtil extends UtilityClass { public static boolean execute(Connection connection, String sql) { try (Statement statement = connection.createStatement()) { LOG.debug(sql); return statement.execute(sql); } catch (SQLException e) { throw new RuntimeSqlException(e); } } static DatabaseMetaData getMetaData(Connection connection); static void commit(Connection connection); static void rollback(Connection connection); static boolean execute(Connection connection, String sql); static PreparedStatement prepare(Connection connection, String sql); }### Answer: @Test void execute() throws SQLException { String sql = RandomStringUtils.randomAlphabetic(30); when(connection.createStatement()).thenReturn(statement); when(statement.execute(sql)).thenReturn(true); boolean result = ConnectionUtil.execute(connection, sql); verify(connection).createStatement(); verify(statement).execute(sql); verify(statement).close(); verifyNoMoreInteractions(connection, statement); assertThat(result, is(true)); } @Test void executeThatThrowsInCreateStatement() throws SQLException { String message = RandomStringUtils.randomAlphabetic(50); when(connection.createStatement()).thenThrow(new SQLException(message)); calling(() -> ConnectionUtil.execute(connection, RandomStringUtils.randomAlphabetic(30))) .shouldThrow(RuntimeSqlException.class) .withCause(SQLException.class) .withMessage(is(message)); verify(connection).createStatement(); verifyNoMoreInteractions(connection); } @Test void executeThatThrowsInStatementExecute() throws SQLException { String message = RandomStringUtils.randomAlphabetic(50); String sql = RandomStringUtils.randomAlphabetic(30); when(connection.createStatement()).thenReturn(statement); when(statement.execute(sql)).thenThrow(new SQLException(message)); calling(() -> ConnectionUtil.execute(connection, sql)) .shouldThrow(RuntimeSqlException.class) .withCause(SQLException.class) .withMessage(is(message)); verify(connection).createStatement(); verify(statement).execute(sql); verify(statement).close(); verifyNoMoreInteractions(connection, statement); }
### Question: ConnectionUtil extends UtilityClass { public static PreparedStatement prepare(Connection connection, String sql) { try { return connection.prepareStatement(sql); } catch (SQLException e) { throw new RuntimeSqlException(e); } } static DatabaseMetaData getMetaData(Connection connection); static void commit(Connection connection); static void rollback(Connection connection); static boolean execute(Connection connection, String sql); static PreparedStatement prepare(Connection connection, String sql); }### Answer: @Test void prepare() throws SQLException { String sql = RandomStringUtils.randomAlphabetic(30); when(connection.prepareStatement(any())).thenReturn(preparedStatement); PreparedStatement actual = ConnectionUtil.prepare(connection, sql); verify(connection).prepareStatement(sql); verifyNoMoreInteractions(connection); assertThat(actual, sameInstance(preparedStatement)); } @Test void prepareThatThrows() throws SQLException { String sql = RandomStringUtils.randomAlphabetic(30); when(connection.prepareStatement(sql)).thenThrow(new SQLException("Syntax error")); calling(() -> ConnectionUtil.prepare(connection, sql)) .shouldThrow(RuntimeSqlException.class) .withCause(SQLException.class) .withMessage(is("Syntax error")); verify(connection).prepareStatement(sql); }
### Question: ForeignKeyName { public static ForeignKeyName parseString(String stringRepresentation) { Matcher matcher = NAME_PATTERN.matcher(stringRepresentation); if (!matcher.matches()) { throw new IllegalArgumentException(stringRepresentation + " is not a valid QualifiedName"); } QualifiedName table = StringUtils.isBlank(matcher.group(1)) ? new QualifiedName("", "", "") : QualifiedName.parseString(matcher.group(1)); return new ForeignKeyName(table, matcher.group(2)); } ForeignKeyName(QualifiedName table, String name); String toString(); @Override boolean equals(Object o); @Override int hashCode(); QualifiedName table(); String name(); Optional<String> catalog(); Optional<String> schema(); Optional<String> tableName(); static ForeignKeyName parseString(String stringRepresentation); }### Answer: @ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @NullValue("NULL") @TestCase({"A.B.C.D", "A", "B", "C", "D"}) @TestCase({"B.C.D", "NULL", "B", "C", "D"}) @TestCase({"C.D", "NULL", "NULL", "C", "D"}) @TestCase({"D", "NULL", "NULL", "NULL", "D"}) void parseString(String input, String expectedCatalog, String expectedSchema, String expectedTable, String expectedName) { ForeignKeyName result = ForeignKeyName.parseString(input); assertThat(result.catalog(), is(Optional.ofNullable(expectedCatalog))); assertThat(result.schema(), is(Optional.ofNullable(expectedSchema))); assertThat(result.tableName(), is(Optional.ofNullable(expectedTable))); assertThat(result.name(), is(expectedName)); }
### Question: StreamUtil extends UtilityClass { public static <T> Stream<T> of(Optional<T> opt) { return opt.map(Stream::of).orElseGet(Stream::empty); } static Stream<T> ofNullable(T value); static Stream<T> ofBlankable(T value); static Stream<T> of(Optional<T> opt); static Stream<Tuple2<T, Long>> zipWithIndex(Stream<? extends T> stream); static Stream<R> mapWithIndex(Stream<T> input, BiFunction<? super T, Long, ? extends R> mapping); static byte[] toByteArray(IntStream stream); }### Answer: @Test void ofEmpty() { Stream<Object> result = StreamUtil.of(Optional.empty()); assertThat(result.count(), is(0L)); } @Test void ofValue() { Stream<String> result = StreamUtil.of(Optional.of("ABC")); assertThat(result.toArray(String[]::new), arrayContaining("ABC")); }
### Question: StreamUtil extends UtilityClass { public static <T> Stream<Tuple2<T, Long>> zipWithIndex(Stream<? extends T> stream) { Iterator<Tuple2<T,Long>> iterator = new Iterator<Tuple2<T,Long>>() { private final Iterator<? extends T> streamIterator = stream.iterator(); private long index = 0; @Override public boolean hasNext() { return streamIterator.hasNext(); } @Override public Tuple2<T,Long> next() { return Tuple.of(streamIterator.next(), index++); } }; return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED | Spliterator.IMMUTABLE), false); } static Stream<T> ofNullable(T value); static Stream<T> ofBlankable(T value); static Stream<T> of(Optional<T> opt); static Stream<Tuple2<T, Long>> zipWithIndex(Stream<? extends T> stream); static Stream<R> mapWithIndex(Stream<T> input, BiFunction<? super T, Long, ? extends R> mapping); static byte[] toByteArray(IntStream stream); }### Answer: @Test void zipWithIndex() { Stream<Tuple2<String, Long>> result = StreamUtil.zipWithIndex(Stream.of("a", "b", "c")); assertThat(result, contains(Tuple.of("a", 0L), Tuple.of("b", 1L), Tuple.of("c", 2L))); }
### Question: StreamUtil extends UtilityClass { public static <T, R> Stream<R> mapWithIndex(Stream<T> input, BiFunction<? super T, Long, ? extends R> mapping) { return zipWithIndex(input).map(tuple -> tuple.map(mapping)); } static Stream<T> ofNullable(T value); static Stream<T> ofBlankable(T value); static Stream<T> of(Optional<T> opt); static Stream<Tuple2<T, Long>> zipWithIndex(Stream<? extends T> stream); static Stream<R> mapWithIndex(Stream<T> input, BiFunction<? super T, Long, ? extends R> mapping); static byte[] toByteArray(IntStream stream); }### Answer: @Test void mapWithIndex() { Stream<String> result = StreamUtil.mapWithIndex(Stream.of("a", "bc", "def"), (s, i) -> s + "." + (i + 1)); assertThat(result, contains("a.1", "bc.2", "def.3")); }
### Question: Delete extends ExecutableStatement { private Delete(Database database, Alias<D> alias) { super(new Scope(database, alias)); this.alias = alias; } private Delete(Database database, Alias<D> alias); static ExpectingWhere delete(Database database, Table<U> table); static ExpectingWhere delete(Database database, Alias<U> alias); }### Answer: @Test void update() { Database database = Database.newBuilder() .defaultSchema("SIESTA") .build(); database.delete(WidgetRow.class) .where(WidgetRow::widgetId).isEqualTo(2L) .and(column(WidgetRow::description).isBetween("C").and(WidgetRow::name) .or(column(WidgetRow::description).isNull())) .execute(transaction); verify(transaction).update(sql.capture(), args.capture()); assertThat(sql.getValue(), is("delete from SIESTA.WIDGET " + "where SIESTA.WIDGET.WIDGET_ID = ? " + "and (" + "SIESTA.WIDGET.DESCRIPTION between ? and SIESTA.WIDGET.NAME " + "or SIESTA.WIDGET.DESCRIPTION is null" + ")")); assertThat(args.getValue(), is(toArray(2L, "C"))); }
### Question: Update extends ExecutableStatement { private Update(Database database, Alias<U> alias) { super(new Scope(database, alias)); this.alias = alias; } private Update(Database database, Alias<U> alias); static InSetExpectingWhere<U> update(Database database, Table<U> table); static InSetExpectingWhere<U> update(Database database, Alias<U> alias); }### Answer: @Test void update() { Database database = Database.newBuilder() .defaultSchema("SIESTA") .table(WidgetRow.class, t -> t.builder(WidgetRow.Builder::build)) .build(); database.update(WidgetRow.class, "w") .set(WidgetRow::name).to("Fred") .set(WidgetRow::description).to(Optional.of("Bob")) .where(WidgetRow::widgetId).isEqualTo(1L) .and(column(WidgetRow::description).isBetween("A").and("w", WidgetRow::name) .or(column(WidgetRow::description).isNull())) .execute(transaction); verify(transaction).update(sql.capture(), args.capture()); assertThat(sql.getValue(), is("update SIESTA.WIDGET w " + "set NAME = ?, " + "DESCRIPTION = ? " + "where w.WIDGET_ID = ? " + "and (" + "w.DESCRIPTION between ? and w.NAME " + "or w.DESCRIPTION is null" + ")")); assertThat(args.getValue(), is(toArray("Fred", "Bob", 1L, "A"))); }
### Question: SelectStatement { public Stream<CommonTableExpression<?>> commonTableExpressions() { return commonTableExpressions.stream(); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void commonTableExpressions() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); sut.addCommonTableExpression(cte); Stream<CommonTableExpression<?>> result = sut.commonTableExpressions(); assertThat(result.collect(toList()), contains(cte)); }
### Question: CastExpression implements TypedExpression<T> { @Override public String label(Scope scope) { return labelGenerator.label(scope); } CastExpression(TypedExpression<F> from, DataType<T> to, DbTypeId<T> toType, BiFunction<DbType<T>,Database,String> toSql); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); @Override String toString(); }### Answer: @Test void label() { CastBuilder<String> builder = new CastBuilder<>(expression); TypedExpression<Integer> sut = builder.asInteger(); when(scope.newLabel()).thenReturn(345L); String result = sut.label(scope); assertThat(result, is("cast_345")); verifyZeroInteractions(expression, scope, dialect, database, resultSet); }
### Question: CastExpression implements TypedExpression<T> { @Override public RowMapper<T> rowMapper(Scope scope, Optional<String> label) { return rs -> to.get(rs, label.orElseGet(() -> label(scope)), scope.database()).orElse(null); } CastExpression(TypedExpression<F> from, DataType<T> to, DbTypeId<T> toType, BiFunction<DbType<T>,Database,String> toSql); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); @Override String toString(); }### Answer: @Test void rowMapper() throws SQLException { when(resultSet.getInt("bob")).thenReturn(44); when(resultSet.wasNull()).thenReturn(false); when(scope.database()).thenReturn(database); when(database.dialect()).thenReturn(dialect); when(dialect.type(DbTypeId.INTEGER)).thenReturn(new DefaultInteger()); CastBuilder<String> builder = new CastBuilder<>(expression); TypedExpression<Integer> sut = builder.asInteger(); RowMapper<Integer> result = sut.rowMapper(scope, Optional.of("bob")); assertThat(result.mapRow(resultSet), is(44)); verifyNoMoreInteractions(expression, scope, dialect, database, resultSet); }
### Question: CastExpression implements TypedExpression<T> { @Override public TypeToken<T> type() { return TypeToken.of(to.javaClass()); } CastExpression(TypedExpression<F> from, DataType<T> to, DbTypeId<T> toType, BiFunction<DbType<T>,Database,String> toSql); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); @Override String toString(); }### Answer: @Test void type() { CastBuilder<String> builder = new CastBuilder<>(expression); TypedExpression<LocalDate> sut = builder.asDate(); TypeToken<LocalDate> result = sut.type(); assertThat(result, is(TypeToken.of(LocalDate.class))); verifyNoMoreInteractions(expression, scope, dialect, database, resultSet); }
### Question: CastExpression implements TypedExpression<T> { @Override public Stream<Object> args(Scope scope) { return from.args(scope); } CastExpression(TypedExpression<F> from, DataType<T> to, DbTypeId<T> toType, BiFunction<DbType<T>,Database,String> toSql); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); @Override String toString(); }### Answer: @Test void args() { when(expression.args(scope)).thenReturn(Stream.of(1, 2)); CastBuilder<String> builder = new CastBuilder<>(expression); TypedExpression<LocalDate> sut = builder.asDate(); Object[] result = sut.args(scope).toArray(); assertThat(result, arrayContaining(1, 2)); verifyNoMoreInteractions(expression, scope, dialect, database, resultSet); }
### Question: CastExpression implements TypedExpression<T> { @Override public Precedence precedence() { return Precedence.UNARY; } CastExpression(TypedExpression<F> from, DataType<T> to, DbTypeId<T> toType, BiFunction<DbType<T>,Database,String> toSql); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); @Override String toString(); }### Answer: @Test void precedence() { CastBuilder<String> builder = new CastBuilder<>(expression); TypedExpression<String> sut = builder.asVarchar(20); Precedence result = sut.precedence(); assertThat(result, is(Precedence.UNARY)); verifyNoMoreInteractions(expression, scope, dialect, database, resultSet); }
### Question: CastExpression implements TypedExpression<T> { @Override public String toString() { return String.format("cast(%s as %s)", from, toSql.apply(new AnsiDialect().type(toType), Database.newBuilder().build())); } CastExpression(TypedExpression<F> from, DataType<T> to, DbTypeId<T> toType, BiFunction<DbType<T>,Database,String> toSql); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); @Override String toString(); }### Answer: @Test void toStringFunction() { when(expression.toString()).thenReturn("input"); CastBuilder<String> builder = new CastBuilder<>(expression); TypedExpression<String> sut = builder.asVarchar(20); String result = sut.toString(); assertThat(result, is("cast(input as varchar(20))")); verifyNoMoreInteractions(expression, scope, dialect, database, resultSet); }
### Question: SequenceExpression implements TypedExpression<T> { @Override public String label(Scope scope) { return labelGenerator.label(scope); } SequenceExpression(Sequence<T> sequence); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); T single(); }### Answer: @Test void label() { SequenceExpression<Integer> sut1 = new SequenceExpression<>(intSequence); SequenceExpression<Integer> sut2 = new SequenceExpression<>(intSequence); when(scope.newLabel()).thenReturn(563L).thenReturn(564L); String label1 = sut1.label(scope); String label2 = sut1.label(scope); String label3 = sut2.label(scope); assertThat(label1, is("sequence_563")); assertThat(label2, is("sequence_563")); assertThat(label3, is("sequence_564")); }
### Question: SequenceExpression implements TypedExpression<T> { @Override public RowMapper<T> rowMapper(Scope scope, Optional<String> label) { return sequence.rowMapper(label.orElseGet(() -> label(scope))); } SequenceExpression(Sequence<T> sequence); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); T single(); }### Answer: @Test void rowMapper() { when(intSequence.rowMapper("fred")).thenReturn(rowMapper); SequenceExpression<Integer> sut = new SequenceExpression<>(intSequence); RowMapper<Integer> result = sut.rowMapper(scope, Optional.of("fred")); assertThat(result, sameInstance(rowMapper)); }
### Question: SequenceExpression implements TypedExpression<T> { @Override public TypeToken<T> type() { return sequence.type(); } SequenceExpression(Sequence<T> sequence); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); T single(); }### Answer: @Test void type() { TypeToken<Integer> intType = TypeToken.of(Integer.class); when(intSequence.type()).thenReturn(intType); SequenceExpression<Integer> sut = new SequenceExpression<>(intSequence); TypeToken<Integer> result = sut.type(); assertThat(result, sameInstance(intType)); }
### Question: SequenceExpression implements TypedExpression<T> { @Override public String sql(Scope scope) { return sequence.sql(); } SequenceExpression(Sequence<T> sequence); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); T single(); }### Answer: @Test void sql() { when(intSequence.sql()).thenReturn("sql to get sequence value"); SequenceExpression<Integer> sut = new SequenceExpression<>(intSequence); String result = sut.sql(scope); assertThat(result, is("sql to get sequence value")); }
### Question: SelectStatement { void addUnion(SelectStatement<RT> next, UnionType unionType) { unions.add(Tuple.of(unionType, next)); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"UNION", "union"}) @TestCase({"UNION_ALL", "union all"}) void addUnion(UnionType unionType, String unionSql) { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); when(projection.sql(any())).thenReturn("*"); when(from.sql(any())).thenReturn(" from foo"); when(union.sqlImpl(any())).thenReturn("select * from bar"); sut.addUnion(union, unionType); String sql = sut.sql(); assertThat(sql, is("select * from foo " + unionSql + " select * from bar")); }
### Question: SequenceExpression implements TypedExpression<T> { @Override public Stream<Object> args(Scope scope) { return Stream.empty(); } SequenceExpression(Sequence<T> sequence); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); T single(); }### Answer: @Test void args() { SequenceExpression<Integer> sut = new SequenceExpression<>(intSequence); List<Object> result = sut.args(scope).collect(toList()); assertThat(result, iterableWithSize(0)); }
### Question: SequenceExpression implements TypedExpression<T> { @Override public Precedence precedence() { return Precedence.UNARY; } SequenceExpression(Sequence<T> sequence); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); T single(); }### Answer: @Test void precedence() { SequenceExpression<Integer> sut = new SequenceExpression<>(intSequence); Precedence result = sut.precedence(); assertThat(result, is(Precedence.UNARY)); }
### Question: SequenceExpression implements TypedExpression<T> { public T single() { return sequence.single(); } SequenceExpression(Sequence<T> sequence); @Override String label(Scope scope); @Override RowMapper<T> rowMapper(Scope scope, Optional<String> label); @Override TypeToken<T> type(); @Override String sql(Scope scope); @Override Stream<Object> args(Scope scope); @Override Precedence precedence(); T single(); }### Answer: @Test void single() { when(intSequence.single()).thenReturn(54321); SequenceExpression<Integer> sut = new SequenceExpression<>(intSequence); int result = sut.single(); assertThat(result, is(54321)); }
### Question: OlapFunction { String label(Scope scope) { return labelGenerator.label(scope); } OlapFunction(String functionName, TypeToken<T> type, TypedExpression<?>... arguments); }### Answer: @Test void label() { when(scope.newLabel()).thenReturn(5L); OlapFunction<Integer> sut = new OlapFunction<>("foo", TypeToken.of(Integer.class), arg1); String result = sut.label(scope); assertThat(result, is("foo_5")); }
### Question: OlapFunction { RowMapper<T> rowMapper(Scope scope, String label) { DataType<T> dataType = scope.database().getDataTypeOf(type); return rs -> dataType.get(rs, label, scope.database()).orElse(null); } OlapFunction(String functionName, TypeToken<T> type, TypedExpression<?>... arguments); }### Answer: @Test void rowMapper() throws SQLException { when(resultSet.getInt("fred")).thenReturn(1034); when(resultSet.wasNull()).thenReturn(false); when(scope.database()).thenReturn(database); when(database.dialect()).thenReturn(dialect); when(dialect.type(DbTypeId.INTEGER)).thenReturn(new DefaultInteger()); when(database.getDataTypeOf(TypeToken.of(Integer.class))).thenReturn(DataType.INTEGER); OlapFunction<Integer> sut = new OlapFunction<>("foo", TypeToken.of(Integer.class), arg1); RowMapper<Integer> result = sut.rowMapper(scope, "fred"); assertThat(result.mapRow(resultSet), is(1034)); verifyNoMoreInteractions(resultSet); }
### Question: OlapFunction { TypeToken<T> type() { return type; } OlapFunction(String functionName, TypeToken<T> type, TypedExpression<?>... arguments); }### Answer: @Test void type() { OlapFunction<Integer> sut = new OlapFunction<>("bar", TypeToken.of(Integer.class), arg1); assertThat(sut.type(), is(TypeToken.of(Integer.class))); }
### Question: OlapFunction { String sql(Scope scope) { return String.format("%s(%s) over (%s)", functionName, argumentsSql(scope), Stream.of(partitionBySql(scope), orderBySql(scope)) .filter(StringUtils::isNotBlank) .collect(joining(" "))); } OlapFunction(String functionName, TypeToken<T> type, TypedExpression<?>... arguments); }### Answer: @Test void sql() { when(arg1.sql(scope)).thenReturn("arg1"); OlapFunction<Integer> sut = new OlapFunction<>("bar", TypeToken.of(Integer.class), arg1); String result = sut.sql(scope); assertThat(result, is("bar(arg1) over ()")); }
### Question: OlapFunction { Stream<Object> args(Scope scope) { return Stream.concat( Stream.concat( Arrays.stream(arguments), partitionBy.stream().flatMap(Collection::stream) ).flatMap(e -> e.args(scope)), orderBy.stream().flatMap(Collection::stream).flatMap(o -> o.args(scope)) ); } OlapFunction(String functionName, TypeToken<T> type, TypedExpression<?>... arguments); }### Answer: @Test void args() { when(arg1.args(scope)).thenReturn(Stream.of("foo", 123L)); OlapFunction<Integer> sut = new OlapFunction<>("bar", TypeToken.of(Integer.class), arg1); Object[] result = sut.args(scope).toArray(); assertThat(result, is(toArray("foo", 123L))); }
### Question: OlapFunction { Precedence precedence() { return Precedence.UNARY; } OlapFunction(String functionName, TypeToken<T> type, TypedExpression<?>... arguments); }### Answer: @Test void precedence() { OlapFunction<Integer> sut = new OlapFunction<>("bar", TypeToken.of(Integer.class), arg1); Precedence result = sut.precedence(); assertThat(result, is(Precedence.UNARY)); }
### Question: SelectStatement { String label(Scope outerScope) { return labelGenerator.label(outerScope); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void label() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); String result = sut.label(sut.scope()); assertThat(result, is("select_1")); }
### Question: TupleBuilder { public String label(Scope scope) { return labelGenerator.label(scope); } String label(Scope scope); String sql(Scope scope); Stream<Object> args(Scope scope); @SuppressWarnings("SameReturnValue") Precedence precedence(); static TupleBuilder1<T1> tuple(Function1<R,T1> methodRef); static TupleBuilder1<T1> tuple(FunctionOptional1<R,T1> methodRef); static TupleBuilder1<T1> tuple(String alias, Function1<R,T1> methodRef); static TupleBuilder1<T1> tuple(String alias, FunctionOptional1<R,T1> methodRef); static TupleBuilder1<T1> tuple(Alias<R> alias, Function1<R,T1> methodRef); static TupleBuilder1<T1> tuple(Alias<R> alias, FunctionOptional1<R,T1> methodRef); }### Answer: @Test void label() { long labelNum = RandomUtils.nextLong(1, 400); when(scope.newLabel()).thenReturn(labelNum); TupleBuilder1<Long> sut = TupleBuilder.tuple(SalespersonRow::salespersonId); String result = sut.label(scope); assertThat(result, is("tuple_" + labelNum)); }
### Question: SelectStatement { Stream<Object> args(Scope outerScope) { Scope innerScope = outerScope.plus(scope); return Stream.of( cteArgs(outerScope), projection.args(innerScope), from.args(innerScope), whereClauseArgs(innerScope), groupByClauseArgs(innerScope), havingClauseArgs(innerScope), unionsArgs(innerScope) ).flatMap(Function.identity()); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void args() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); when(projection.args(any())).thenReturn(Stream.of("ABC")); when(from.args(any())).thenReturn(Stream.of(1, 2.4)); Stream<Object> result = sut.args(sut.scope()); assertThat(result.toArray(), arrayContaining("ABC", 1, 2.4)); }
### Question: Sequence { public SequenceExpression<T> nextVal() { return new SequenceExpression<>(this); } private Sequence(Builder<T> builder); SequenceExpression<T> nextVal(); T single(); TypeToken<T> type(); RowMapper<T> rowMapper(String label); String name(); String sql(); static Builder<T> newBuilder(); }### Answer: @Test void nextVal() { when(database.dialect()).thenReturn(dialect); when(dialect.nextFromSequence("TOM", "MYSCHEMA", "TEST_SEQ")).thenReturn("select next value from TEST_SEQ"); Sequence<Integer> sut = createSut(); SequenceExpression<Integer> result = sut.nextVal(); assertThat(result.sql(new Scope(database)), is("select next value from TEST_SEQ")); }
### Question: Sequence { public T single() { return single(database.getDefaultSqlExecutor()); } private Sequence(Builder<T> builder); SequenceExpression<T> nextVal(); T single(); TypeToken<T> type(); RowMapper<T> rowMapper(String label); String name(); String sql(); static Builder<T> newBuilder(); }### Answer: @Test void single() { when(database.select(Mockito.<SequenceExpression<Integer>>any(), eq("TEST_SEQ"))).thenReturn(select); when(database.getDefaultSqlExecutor()).thenReturn(sqlExecutor); when(select.single(sqlExecutor)).thenReturn(501); Sequence<Integer> sut = createSut(); Integer single = sut.single(); assertThat(single, is(501)); }
### Question: SelectStatement { @NotNull private Stream<Object> cteArgs(Scope actualScope) { return actualScope.isOutermost() ? commonTableExpressions().flatMap(cte -> cte.args(actualScope)) : Stream.empty(); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void cteArgs() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); when(projection.args(any())).thenReturn(Stream.of("ABC")); when(from.args(any())).thenReturn(Stream.of(1, 2.4)); when(cte.args(any())).thenReturn(Stream.of("Foo", "Bar")); sut.addCommonTableExpression(cte); Stream<Object> result = sut.args(sut.scope()); assertThat(result.toArray(), arrayContaining("Foo", "Bar", "ABC", 1, 2.4)); }
### Question: Sequence { public TypeToken<T> type() { return TypeToken.of(dataType.javaClass()); } private Sequence(Builder<T> builder); SequenceExpression<T> nextVal(); T single(); TypeToken<T> type(); RowMapper<T> rowMapper(String label); String name(); String sql(); static Builder<T> newBuilder(); }### Answer: @Test void type() { Sequence<Integer> sut = createSut(); TypeToken<Integer> result = sut.type(); assertThat(result, is(TypeToken.of(Integer.class))); }
### Question: Sequence { public RowMapper<T> rowMapper(String label) { return rs -> dataType.get(rs, label, database).orElse(null); } private Sequence(Builder<T> builder); SequenceExpression<T> nextVal(); T single(); TypeToken<T> type(); RowMapper<T> rowMapper(String label); String name(); String sql(); static Builder<T> newBuilder(); }### Answer: @Test void rowMapper() throws SQLException { when(database.dialect()).thenReturn(dialect); when(dialect.type(DbTypeId.INTEGER)).thenReturn(new DefaultInteger()); when(resultSet.getInt("bob")).thenReturn(1034); Sequence<Integer> sut = createSut(); RowMapper<Integer> result = sut.rowMapper("bob"); assertThat(result, notNullValue()); assertThat(result.mapRow(resultSet), is(1034)); }
### Question: Sequence { public String sql() { return database.dialect().nextFromSequence(catalog, schema, sequenceName); } private Sequence(Builder<T> builder); SequenceExpression<T> nextVal(); T single(); TypeToken<T> type(); RowMapper<T> rowMapper(String label); String name(); String sql(); static Builder<T> newBuilder(); }### Answer: @Test void sql() { when(database.dialect()).thenReturn(dialect); when(dialect.nextFromSequence("TOM", "MYSCHEMA", "TEST_SEQ")).thenReturn("get the next sequence value"); Sequence<Integer> sut = createSut(); String result = sut.sql(); assertThat(result, is("get the next sequence value")); }
### Question: Alias { public String inWhereClause() { if (isDual()) { return table.database().dialect().dual(); } return aliasName .map(a -> String.format("%s %s", table.qualifiedName(), a)) .orElseGet(table::qualifiedName); } protected Alias(Table<R> table, Optional<String> aliasName); @Override boolean equals(Object o); @Override int hashCode(); TypeToken<R> type(); String inWhereClause(); String inSelectClauseSql(String columnName); String inSelectClauseLabel(String columnName); ExpressionBuilder<T,BooleanExpression> column(Function1<R,T> getter); ExpressionBuilder<T,BooleanExpression> column(FunctionOptional1<R,T> getter); Table<R> table(); Optional<String> aliasName(); Column<T,R> column(MethodInfo<R,T> methodInfo); RowMapper<R> rowMapper(); DynamicRowMapper<R> dynamicRowMapper(); static Alias<U> of(Table<U> table); static Alias<U> of(Table<U> table, String aliasName); }### Answer: @Test void inWhereClause() { when(widgetTable.qualifiedName()).thenReturn("SCHEMA.WIDGET"); when(widgetTable.rowType()).thenReturn(TypeToken.of(WidgetRow.class)); Alias<WidgetRow> sut = Alias.of(widgetTable, "bob"); String result = sut.inWhereClause(); assertThat(result, is("SCHEMA.WIDGET bob")); }
### Question: Alias { public String inSelectClauseSql(String columnName) { return String.format("%s.%s", aliasName.orElseGet(table::qualifiedName), columnName); } protected Alias(Table<R> table, Optional<String> aliasName); @Override boolean equals(Object o); @Override int hashCode(); TypeToken<R> type(); String inWhereClause(); String inSelectClauseSql(String columnName); String inSelectClauseLabel(String columnName); ExpressionBuilder<T,BooleanExpression> column(Function1<R,T> getter); ExpressionBuilder<T,BooleanExpression> column(FunctionOptional1<R,T> getter); Table<R> table(); Optional<String> aliasName(); Column<T,R> column(MethodInfo<R,T> methodInfo); RowMapper<R> rowMapper(); DynamicRowMapper<R> dynamicRowMapper(); static Alias<U> of(Table<U> table); static Alias<U> of(Table<U> table, String aliasName); }### Answer: @Test void inSelectClauseSql() { Alias<WidgetRow> sut = Alias.of(widgetTable, "fred"); String result = sut.inSelectClauseSql("WIDGET_ID"); assertThat(result, is("fred.WIDGET_ID")); }
### Question: Alias { public String inSelectClauseLabel(String columnName) { return String.format("%s_%s", columnLabelPrefix(), columnName); } protected Alias(Table<R> table, Optional<String> aliasName); @Override boolean equals(Object o); @Override int hashCode(); TypeToken<R> type(); String inWhereClause(); String inSelectClauseSql(String columnName); String inSelectClauseLabel(String columnName); ExpressionBuilder<T,BooleanExpression> column(Function1<R,T> getter); ExpressionBuilder<T,BooleanExpression> column(FunctionOptional1<R,T> getter); Table<R> table(); Optional<String> aliasName(); Column<T,R> column(MethodInfo<R,T> methodInfo); RowMapper<R> rowMapper(); DynamicRowMapper<R> dynamicRowMapper(); static Alias<U> of(Table<U> table); static Alias<U> of(Table<U> table, String aliasName); }### Answer: @Test void inSelectClauseLabel() { Alias<WidgetRow> sut = Alias.of(widgetTable, "fred"); String result = sut.inSelectClauseLabel("WIDGET_ID"); assertThat(result, is("fred_WIDGET_ID")); }
### Question: JdbcTransaction implements Transaction { Connection connection() { return connection; } JdbcTransaction(JdbcSqlExecutor sqlExecutor); @Override void commit(); @Override void rollback(); @Override List<T> query(String sql, Object[] args, RowMapper<T> rowMapper); @Override CompletableFuture<List<T>> queryAsync(String sql, Object[] args, RowMapper<T> rowMapper); @Override Stream<T> stream(String sql, Object[] args, RowMapper<T> rowMapper); @Override int update(String sql, Object[] args); @Override boolean execute(String sql, Object[] args); @Override CompletableFuture<Integer> updateAsync(String sql, Object[] args); @Override void close(); }### Answer: @Test void connection() throws SQLException { when(sqlExecutor.connect()).thenReturn(connection); JdbcTransaction sut = new JdbcTransaction(sqlExecutor); Connection result = sut.connection(); assertThat(result, sameInstance(connection)); verify(connection).setAutoCommit(false); verifyNoMoreInteractions(sqlExecutor, connection); }
### Question: JdbcTransaction implements Transaction { @Override public void commit() { ConnectionUtil.commit(connection); } JdbcTransaction(JdbcSqlExecutor sqlExecutor); @Override void commit(); @Override void rollback(); @Override List<T> query(String sql, Object[] args, RowMapper<T> rowMapper); @Override CompletableFuture<List<T>> queryAsync(String sql, Object[] args, RowMapper<T> rowMapper); @Override Stream<T> stream(String sql, Object[] args, RowMapper<T> rowMapper); @Override int update(String sql, Object[] args); @Override boolean execute(String sql, Object[] args); @Override CompletableFuture<Integer> updateAsync(String sql, Object[] args); @Override void close(); }### Answer: @Test void commit() throws SQLException { when(sqlExecutor.connect()).thenReturn(connection); JdbcTransaction sut = new JdbcTransaction(sqlExecutor); sut.commit(); verify(connection).setAutoCommit(false); verify(connection).commit(); verifyNoMoreInteractions(sqlExecutor, connection); }
### Question: JdbcTransaction implements Transaction { @Override public void rollback() { ConnectionUtil.rollback(connection); } JdbcTransaction(JdbcSqlExecutor sqlExecutor); @Override void commit(); @Override void rollback(); @Override List<T> query(String sql, Object[] args, RowMapper<T> rowMapper); @Override CompletableFuture<List<T>> queryAsync(String sql, Object[] args, RowMapper<T> rowMapper); @Override Stream<T> stream(String sql, Object[] args, RowMapper<T> rowMapper); @Override int update(String sql, Object[] args); @Override boolean execute(String sql, Object[] args); @Override CompletableFuture<Integer> updateAsync(String sql, Object[] args); @Override void close(); }### Answer: @Test void rollback() throws SQLException { when(sqlExecutor.connect()).thenReturn(connection); JdbcTransaction sut = new JdbcTransaction(sqlExecutor); sut.rollback(); verify(connection).setAutoCommit(false); verify(connection).rollback(); verifyNoMoreInteractions(sqlExecutor, connection); }
### Question: JdbcTransaction implements Transaction { @Override public <T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper) { return sqlExecutor.query(connection, sql, args, rowMapper); } JdbcTransaction(JdbcSqlExecutor sqlExecutor); @Override void commit(); @Override void rollback(); @Override List<T> query(String sql, Object[] args, RowMapper<T> rowMapper); @Override CompletableFuture<List<T>> queryAsync(String sql, Object[] args, RowMapper<T> rowMapper); @Override Stream<T> stream(String sql, Object[] args, RowMapper<T> rowMapper); @Override int update(String sql, Object[] args); @Override boolean execute(String sql, Object[] args); @Override CompletableFuture<Integer> updateAsync(String sql, Object[] args); @Override void close(); }### Answer: @Test void query() throws SQLException { when(sqlExecutor.connect()).thenReturn(connection); JdbcTransaction sut = new JdbcTransaction(sqlExecutor); String sql = RandomStringUtils.randomAlphabetic(20, 30); Object[] args = new Object[0]; RowMapper<String> rowMapper = s -> "Hello"; List<String> list = ImmutableList.of("A", "B"); when(sqlExecutor.query(connection, sql, args, rowMapper)).thenReturn(list); List<String> result = sut.query(sql, args, rowMapper); assertThat(result, sameInstance(list)); verify(connection).setAutoCommit(false); verify(sqlExecutor).query(connection, sql, args, rowMapper); verifyNoMoreInteractions(sqlExecutor, connection); }
### Question: SelectStatement { Projection projection() { return projection; } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer: @Test void projection() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); Projection result = sut.projection(); assertThat(result, sameInstance(projection)); }
### Question: JdbcTransaction implements Transaction { @Override public <T> Stream<T> stream(String sql, Object[] args, RowMapper<T> rowMapper) { return autoCloseable.add(sqlExecutor.stream(connection, sql, args, rowMapper, new CompositeAutoCloseable())); } JdbcTransaction(JdbcSqlExecutor sqlExecutor); @Override void commit(); @Override void rollback(); @Override List<T> query(String sql, Object[] args, RowMapper<T> rowMapper); @Override CompletableFuture<List<T>> queryAsync(String sql, Object[] args, RowMapper<T> rowMapper); @Override Stream<T> stream(String sql, Object[] args, RowMapper<T> rowMapper); @Override int update(String sql, Object[] args); @Override boolean execute(String sql, Object[] args); @Override CompletableFuture<Integer> updateAsync(String sql, Object[] args); @Override void close(); }### Answer: @Test void stream() throws SQLException { when(sqlExecutor.connect()).thenReturn(connection); JdbcTransaction sut = new JdbcTransaction(sqlExecutor); String sql = RandomStringUtils.randomAlphabetic(20, 30); Object[] args = new Object[0]; RowMapper<String> rowMapper = s -> "Hello"; when(sqlExecutor.stream(eq(connection), eq(sql), eq(args), eq(rowMapper), any())).thenReturn(stream); Stream<String> result = sut.stream(sql, args, rowMapper); assertThat(result, sameInstance(stream)); verify(connection).setAutoCommit(false); verify(sqlExecutor).stream(eq(connection), eq(sql), eq(args), eq(rowMapper), any()); verifyNoMoreInteractions(sqlExecutor, connection); }
### Question: JdbcTransaction implements Transaction { @Override public int update(String sql, Object[] args) { return sqlExecutor.update(connection, sql, args); } JdbcTransaction(JdbcSqlExecutor sqlExecutor); @Override void commit(); @Override void rollback(); @Override List<T> query(String sql, Object[] args, RowMapper<T> rowMapper); @Override CompletableFuture<List<T>> queryAsync(String sql, Object[] args, RowMapper<T> rowMapper); @Override Stream<T> stream(String sql, Object[] args, RowMapper<T> rowMapper); @Override int update(String sql, Object[] args); @Override boolean execute(String sql, Object[] args); @Override CompletableFuture<Integer> updateAsync(String sql, Object[] args); @Override void close(); }### Answer: @Test void update() throws SQLException { when(sqlExecutor.connect()).thenReturn(connection); JdbcTransaction sut = new JdbcTransaction(sqlExecutor); String sql = RandomStringUtils.randomAlphabetic(20, 30); Object[] args = new Object[0]; int rowsUpdated = RandomValues.randomShort(); when(sqlExecutor.update(connection, sql, args)).thenReturn(rowsUpdated); int result = sut.update(sql, args); assertThat(result, is(rowsUpdated)); verify(connection).setAutoCommit(false); verify(sqlExecutor).update(connection, sql, args); verifyNoMoreInteractions(sqlExecutor, connection); }
### Question: JdbcTransaction implements Transaction { @Override public void close() { rollback(); autoCloseable.close(); } JdbcTransaction(JdbcSqlExecutor sqlExecutor); @Override void commit(); @Override void rollback(); @Override List<T> query(String sql, Object[] args, RowMapper<T> rowMapper); @Override CompletableFuture<List<T>> queryAsync(String sql, Object[] args, RowMapper<T> rowMapper); @Override Stream<T> stream(String sql, Object[] args, RowMapper<T> rowMapper); @Override int update(String sql, Object[] args); @Override boolean execute(String sql, Object[] args); @Override CompletableFuture<Integer> updateAsync(String sql, Object[] args); @Override void close(); }### Answer: @Test void close() throws SQLException { when(sqlExecutor.connect()).thenReturn(connection); JdbcTransaction sut = new JdbcTransaction(sqlExecutor); sut.close(); verify(connection).setAutoCommit(false); verify(connection).rollback(); verify(connection).close(); verifyNoMoreInteractions(sqlExecutor, connection); }