Skip to content

Commit 17a37a5

Browse files
committed
feat: use first successful random factory method
Instead of running all factory methods and then choosing one at random, we can choose one at random and use it if it is successful. Refs: JF-77
1 parent 2c17ebb commit 17a37a5

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

src/main/java/com/github/nylle/javafixture/InstanceFactory.java

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import java.util.ArrayDeque;
1616
import java.util.ArrayList;
1717
import java.util.Collection;
18+
import java.util.Collections;
1819
import java.util.Deque;
1920
import java.util.HashMap;
2021
import java.util.HashSet;
@@ -65,19 +66,16 @@ public <T> T construct(final SpecimenType<T> type, CustomizationContext customiz
6566
}
6667

6768
public <T> T manufacture(final SpecimenType<T> type, CustomizationContext customizationContext) {
68-
var results = type.getFactoryMethods()
69+
var factoryMethods = type.getFactoryMethods();
70+
Collections.shuffle(factoryMethods);
71+
var results = factoryMethods
6972
.stream()
7073
.filter(x -> Modifier.isPublic(x.getModifiers()))
7174
.map(x -> manufactureOrNull(x, type, customizationContext))
7275
.filter(x -> x != null)
73-
.map(x -> (T) x)
74-
.collect(toList());
75-
76-
if (results.isEmpty()) {
77-
throw new SpecimenException(format("Cannot manufacture %s", type.asClass()));
78-
}
76+
.findFirst();
7977

80-
return results.get(random.nextInt(results.size()));
78+
return results.orElseThrow(() -> new SpecimenException(format("Cannot manufacture %s", type.asClass())));
8179
}
8280

8381
public <T> T instantiate(final SpecimenType<T> type) {
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.github.nylle.javafixture;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import java.nio.charset.Charset;
6+
7+
import static com.github.nylle.javafixture.Fixture.fixture;
8+
import static org.assertj.core.api.Assertions.assertThat;
9+
10+
class CharsetTest {
11+
12+
@Test
13+
void charsetTest() {
14+
var charset = fixture().create(java.nio.charset.Charset.class);
15+
assertThat( charset ).isNotNull();
16+
}
17+
18+
19+
public static class WithCharSet {
20+
private Charset charset;
21+
}
22+
}

0 commit comments

Comments
 (0)