Skip to content

Commit 46fe660

Browse files
Hans Zuidervaarthanszt
authored andcommitted
Extension of to stream converter method.
Examples of benefits: - Kotlin Sequence support for @testfactory - Kotlin Sequence support for @MethodSource - Classes that expose an Iterator returning method, can be converted to a stream. Issue: #3376 I hereby agree to the terms of the JUnit Contributor License Agreement.
1 parent c9d8cb1 commit 46fe660

File tree

6 files changed

+186
-9
lines changed

6 files changed

+186
-9
lines changed

documentation/src/docs/asciidoc/user-guide/writing-tests.adoc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2480,7 +2480,7 @@ generated at runtime by a factory method that is annotated with `@TestFactory`.
24802480
In contrast to `@Test` methods, a `@TestFactory` method is not itself a test case but
24812481
rather a factory for test cases. Thus, a dynamic test is the product of a factory.
24822482
Technically speaking, a `@TestFactory` method must return a single `DynamicNode` or a
2483-
`Stream`, `Collection`, `Iterable`, `Iterator`, or array of `DynamicNode` instances.
2483+
`Stream`, `Collection`, `Iterable`, `Iterator`, an `Iterator` providing class or array of `DynamicNode` instances.
24842484
Instantiable subclasses of `DynamicNode` are `DynamicContainer` and `DynamicTest`.
24852485
`DynamicContainer` instances are composed of a _display name_ and a list of dynamic child
24862486
nodes, enabling the creation of arbitrarily nested hierarchies of dynamic nodes.

junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/descriptor/TestFactoryTestDescriptor.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ private Stream<DynamicNode> toDynamicNodeStream(Object testFactoryMethodResult)
132132

133133
private JUnitException invalidReturnTypeException(Throwable cause) {
134134
String message = String.format(
135-
"@TestFactory method [%s] must return a single %2$s or a Stream, Collection, Iterable, Iterator, or array of %2$s.",
135+
"@TestFactory method [%s] must return a single %2$s or a Stream, Collection, Iterable, Iterator, Iterator-source or array of %2$s.",
136136
getTestMethod().toGenericString(), DynamicNode.class.getName());
137137
return new JUnitException(message, cause);
138138
}

junit-platform-commons/src/main/java/org/junit/platform/commons/util/CollectionUtils.java

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import static org.apiguardian.api.API.Status.INTERNAL;
1919

2020
import java.lang.reflect.Array;
21+
import java.lang.reflect.Method;
2122
import java.util.Arrays;
2223
import java.util.Collection;
2324
import java.util.Collections;
@@ -27,6 +28,7 @@
2728
import java.util.ListIterator;
2829
import java.util.Optional;
2930
import java.util.Set;
31+
import java.util.Spliterator;
3032
import java.util.function.Consumer;
3133
import java.util.stream.Collector;
3234
import java.util.stream.DoubleStream;
@@ -35,7 +37,9 @@
3537
import java.util.stream.Stream;
3638

3739
import org.apiguardian.api.API;
40+
import org.junit.platform.commons.JUnitException;
3841
import org.junit.platform.commons.PreconditionViolationException;
42+
import org.junit.platform.commons.function.Try;
3943

4044
/**
4145
* Collection of utilities for working with {@link Collection Collections}.
@@ -122,7 +126,7 @@ public static <T> Set<T> toSet(T[] values) {
122126
* returned, so if more control over the returned list is required,
123127
* consider creating a new {@code Collector} implementation like the
124128
* following:
125-
*
129+
* <p>
126130
* <pre class="code">
127131
* public static &lt;T&gt; Collector&lt;T, ?, List&lt;T&gt;&gt; toUnmodifiableList(Supplier&lt;List&lt;T&gt;&gt; listSupplier) {
128132
* return Collectors.collectingAndThen(Collectors.toCollection(listSupplier), Collections::unmodifiableList);
@@ -161,7 +165,11 @@ public static boolean isConvertibleToStream(Class<?> type) {
161165
|| Iterable.class.isAssignableFrom(type)//
162166
|| Iterator.class.isAssignableFrom(type)//
163167
|| Object[].class.isAssignableFrom(type)//
164-
|| (type.isArray() && type.getComponentType().isPrimitive()));
168+
|| (type.isArray() && type.getComponentType().isPrimitive())//
169+
|| Arrays.stream(type.getMethods())//
170+
.filter(m -> m.getName().equals("iterator"))//
171+
.map(Method::getReturnType)//
172+
.anyMatch(returnType -> returnType == Iterator.class));
165173
}
166174

167175
/**
@@ -177,6 +185,7 @@ public static boolean isConvertibleToStream(Class<?> type) {
177185
* <li>{@link Iterator}</li>
178186
* <li>{@link Object} array</li>
179187
* <li>primitive array</li>
188+
* <li>An object that contains a method with name `iterator` returning an Iterator object</li>
180189
* </ul>
181190
*
182191
* @param object the object to convert into a stream; never {@code null}
@@ -223,8 +232,31 @@ public static Stream<?> toStream(Object object) {
223232
if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) {
224233
return IntStream.range(0, Array.getLength(object)).mapToObj(i -> Array.get(object, i));
225234
}
226-
throw new PreconditionViolationException(
227-
"Cannot convert instance of " + object.getClass().getName() + " into a Stream: " + object);
235+
return tryConvertToStreamByReflection(object);
236+
}
237+
238+
private static Stream<?> tryConvertToStreamByReflection(Object object) {
239+
Preconditions.notNull(object, "Object must not be null");
240+
try {
241+
String name = "iterator";
242+
Method method = object.getClass().getMethod(name);
243+
if (method.getReturnType() == Iterator.class) {
244+
return stream(() -> tryIteratorToSpliterator(object, method), ORDERED, false);
245+
}
246+
else {
247+
throw new PreconditionViolationException(
248+
"Method with name 'iterator' does not return " + Iterator.class.getName());
249+
}
250+
}
251+
catch (NoSuchMethodException | IllegalStateException e) {
252+
throw new PreconditionViolationException(//
253+
"Cannot convert instance of " + object.getClass().getName() + " into a Stream: " + object, e);
254+
}
255+
}
256+
257+
private static Spliterator<?> tryIteratorToSpliterator(Object object, Method method) {
258+
return Try.call(() -> spliteratorUnknownSize((Iterator<?>) method.invoke(object), ORDERED))//
259+
.getOrThrow(e -> new JUnitException("Cannot invoke method " + method.getName() + " onto " + object, e));//
228260
}
229261

230262
/**
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
* Copyright 2015-2025 the original author or authors.
3+
*
4+
* All rights reserved. This program and the accompanying materials are
5+
* made available under the terms of the Eclipse Public License v2.0 which
6+
* accompanies this distribution and is available at
7+
*
8+
* https://www.eclipse.org/legal/epl-v20.html
9+
*/
10+
package org.junit.jupiter.api
11+
12+
import org.junit.jupiter.api.Assertions.assertEquals
13+
import org.junit.jupiter.api.DynamicTest.dynamicTest
14+
import java.math.BigDecimal
15+
import java.math.BigDecimal.ONE
16+
import java.math.MathContext
17+
import java.math.BigInteger as BigInt
18+
import java.math.RoundingMode as Rounding
19+
20+
/**
21+
* Unit tests for JUnit Jupiter [TestFactory] use in kotlin classes.
22+
*
23+
* @since 5.12
24+
*/
25+
class KotlinDynamicTests {
26+
@Nested
27+
inner class SequenceReturningTestFactoryTests {
28+
@TestFactory
29+
fun `Dynamic tests returned as Kotlin sequence`() =
30+
generateSequence(0) { it + 2 }
31+
.map { dynamicTest("$it should be even") { assertEquals(0, it % 2) } }
32+
.take(10)
33+
34+
@TestFactory
35+
fun `Consecutive fibonacci nr ratios, should converge to golden ratio as n increases`(): Sequence<DynamicTest> {
36+
val scale = 5
37+
val goldenRatio =
38+
(ONE + 5.toBigDecimal().sqrt(MathContext(scale + 10, Rounding.HALF_UP)))
39+
.divide(2.toBigDecimal(), scale, Rounding.HALF_UP)
40+
41+
fun shouldApproximateGoldenRatio(
42+
cur: BigDecimal,
43+
next: BigDecimal
44+
) = next.divide(cur, scale, Rounding.HALF_UP).let {
45+
dynamicTest("$cur / $next = $it should approximate the golden ratio in $scale decimals") {
46+
assertEquals(goldenRatio, it)
47+
}
48+
}
49+
return generateSequence(BigInt.ONE to BigInt.ONE) { (cur, next) -> next to cur + next }
50+
.map { (cur) -> cur.toBigDecimal() }
51+
.zipWithNext(::shouldApproximateGoldenRatio)
52+
.drop(14)
53+
.take(10)
54+
}
55+
}
56+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright 2015-2025 the original author or authors.
3+
*
4+
* All rights reserved. This program and the accompanying materials are
5+
* made available under the terms of the Eclipse Public License v2.0 which
6+
* accompanies this distribution and is available at
7+
*
8+
* https://www.eclipse.org/legal/epl-v20.html
9+
*/
10+
package org.junit.jupiter.params.aggregator
11+
12+
import org.junit.jupiter.api.Assertions.assertEquals
13+
import org.junit.jupiter.params.ParameterizedTest
14+
import org.junit.jupiter.params.provider.Arguments.arguments
15+
import org.junit.jupiter.params.provider.MethodSource
16+
import java.time.Month
17+
18+
/**
19+
* Tests for ParameterizedTest kotlin compatibility
20+
*/
21+
object KotlinParameterizedTests {
22+
@ParameterizedTest
23+
@MethodSource("dataProvidedByKotlinSequence")
24+
fun `a method source can be supplied by a Sequence returning method`(
25+
value: Int,
26+
month: Month
27+
) {
28+
assertEquals(value, month.value)
29+
}
30+
31+
@JvmStatic
32+
private fun dataProvidedByKotlinSequence() =
33+
sequenceOf(
34+
arguments(1, Month.JANUARY),
35+
arguments(3, Month.MARCH),
36+
arguments(8, Month.AUGUST),
37+
arguments(5, Month.MAY),
38+
arguments(12, Month.DECEMBER)
39+
)
40+
}

platform-tests/src/test/java/org/junit/platform/commons/util/CollectionUtilsTests.java

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
import java.util.Iterator;
2626
import java.util.List;
2727
import java.util.Set;
28+
import java.util.Spliterator;
29+
import java.util.Spliterators;
2830
import java.util.concurrent.atomic.AtomicBoolean;
2931
import java.util.stream.DoubleStream;
3032
import java.util.stream.IntStream;
@@ -139,6 +141,7 @@ class StreamConversion {
139141
Collection.class, //
140142
Iterable.class, //
141143
Iterator.class, //
144+
IteratorProvider.class, //
142145
Object[].class, //
143146
String[].class, //
144147
int[].class, //
@@ -160,10 +163,11 @@ static Stream<Object> objectsConvertibleToStreams() {
160163
Stream.of("cat", "dog"), //
161164
DoubleStream.of(42.3), //
162165
IntStream.of(99), //
163-
LongStream.of(100000000), //
166+
LongStream.of(100_000_000), //
164167
Set.of(1, 2, 3), //
165168
Arguments.of((Object) new Object[] { 9, 8, 7 }), //
166-
new int[] { 5, 10, 15 }//
169+
new int[] { 5, 10, 15 }, //
170+
IteratorProvider.of(new Integer[] { 1, 2, 3, 4, 5 })//
167171
);
168172
}
169173

@@ -174,6 +178,8 @@ static Stream<Object> objectsConvertibleToStreams() {
174178
Object.class, //
175179
Integer.class, //
176180
String.class, //
181+
IteratorProviderNotUsable.class, //
182+
Spliterator.class, //
177183
int.class, //
178184
boolean.class //
179185
})
@@ -242,7 +248,7 @@ void toStreamWithLongStream() {
242248
}
243249

244250
@Test
245-
@SuppressWarnings({ "unchecked", "serial" })
251+
@SuppressWarnings({ "unchecked" })
246252
void toStreamWithCollection() {
247253
var collectionStreamClosed = new AtomicBoolean(false);
248254
Collection<String> input = new ArrayList<>() {
@@ -287,6 +293,24 @@ void toStreamWithIterator() {
287293
assertThat(result).containsExactly("foo", "bar");
288294
}
289295

296+
@Test
297+
@SuppressWarnings("unchecked")
298+
void toStreamWithIteratorProvider() {
299+
final var input = IteratorProvider.of(new String[] { "foo", "bar" });
300+
301+
final var result = (Stream<String>) CollectionUtils.toStream(input);
302+
303+
assertThat(result).containsExactly("foo", "bar");
304+
}
305+
306+
@Test
307+
void throwWhenIteratorNamedMethodDoesNotReturnAnIterator() {
308+
var o = IteratorProviderNotUsable.of(new String[] { "Test" });
309+
var e = assertThrows(PreconditionViolationException.class, () -> CollectionUtils.toStream(o));
310+
311+
assertEquals("Method with name 'iterator' does not return java.util.Iterator", e.getMessage());
312+
}
313+
290314
@Test
291315
@SuppressWarnings("unchecked")
292316
void toStreamWithArray() {
@@ -355,4 +379,29 @@ public Object convert(Object source, ParameterContext context) throws ArgumentCo
355379
}
356380
}
357381
}
382+
383+
/**
384+
* An interface that has a method with name 'iterator', returning a java.util/Iterator as a return type
385+
*/
386+
private interface IteratorProvider<T> {
387+
388+
@SuppressWarnings("unused")
389+
Iterator<T> iterator();
390+
391+
static <T> IteratorProvider<T> of(T[] elements) {
392+
return () -> Spliterators.iterator(Arrays.spliterator(elements));
393+
}
394+
}
395+
396+
/**
397+
* An interface that has a method with name 'iterator', but does not return java.util/Iterator as a return type
398+
*/
399+
private interface IteratorProviderNotUsable {
400+
@SuppressWarnings("unused")
401+
Object iterator();
402+
403+
static <T> IteratorProviderNotUsable of(T[] elements) {
404+
return () -> Spliterators.iterator(Arrays.spliterator(elements));
405+
}
406+
}
358407
}

0 commit comments

Comments
 (0)