From 8c2c131f612151e9728e6a5c2f5c88ed329fd492 Mon Sep 17 00:00:00 2001 From: Andreas Kutschera Date: Sat, 31 Jan 2026 12:57:30 +0100 Subject: [PATCH] fix: remove constructed objects from cache #125 When we cannot fill an object via reflection (e.g. records), then we need to remove the object from the cache after we created it. We need to do this in order to actually fill sets with more than one member --- .../nylle/javafixture/specimen/ObjectSpecimen.java | 2 +- .../javafixture/specimen/CollectionSpecimenTest.java | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/nylle/javafixture/specimen/ObjectSpecimen.java b/src/main/java/com/github/nylle/javafixture/specimen/ObjectSpecimen.java index f114b67..eef6007 100644 --- a/src/main/java/com/github/nylle/javafixture/specimen/ObjectSpecimen.java +++ b/src/main/java/com/github/nylle/javafixture/specimen/ObjectSpecimen.java @@ -68,7 +68,7 @@ private T populate(CustomizationContext customizationContext) { .build(SpecimenType.fromClass(field.getGenericType())) .create(customizationContext.newForField(field.getName()), reflector.getFieldAnnotations(field))))); } catch (SpecimenException ex) { - return context.overwrite(type, instanceFactory.construct(type, customizationContext)); + context.overwrite(type, instanceFactory.construct(type, customizationContext)); } return context.remove(type); } diff --git a/src/test/java/com/github/nylle/javafixture/specimen/CollectionSpecimenTest.java b/src/test/java/com/github/nylle/javafixture/specimen/CollectionSpecimenTest.java index 0a5c53d..0a21864 100644 --- a/src/test/java/com/github/nylle/javafixture/specimen/CollectionSpecimenTest.java +++ b/src/test/java/com/github/nylle/javafixture/specimen/CollectionSpecimenTest.java @@ -141,6 +141,17 @@ void createHashSetFromSetInterface() { assertThat(actual.size()).isEqualTo(2); } + @Test + void createSetWhenObjectIsCreatedWithConstructor() { + var sut = new CollectionSpecimen<>(new SpecimenType>() {}, context, specimenFactory); + + var actual = sut.create(noContext(), new Annotation[0]); + + assertThat(actual).isInstanceOf(HashSet.class); + assertThat(actual.stream().allMatch(x -> x.getClass().equals(Throwable.class))).isTrue(); + assertThat(actual.size()).isEqualTo(2); + } + @Test void createLinkedBlockingDequeFromBlockingDequeInterface() { var sut = new CollectionSpecimen<>(new SpecimenType>() {}, context, specimenFactory);