Catalogue / mapstruct-mapper-tests
mapstruct-mapper-tests
Older skill: source not recordedSignedPlans and writes isolated unit tests for MapStruct mappers and hand-written converters, covering field and renamed mappings, null strategies, collections, nested objects, enum translation, expressions, round trips, and partial updates. Use when the user asks to "test this mapper", "cover DTO to enti…--- name: mapstruct-mapper-tests description: >- Plans and writes isolated unit tests for MapStruct mappers and hand-written converters, covering field and renamed mappings, null strategies, collections, nested objects, enum translation, expressions, round trips, and partial updates. Use when the user asks to "test this mapper", "cover DTO to entity conversions", "verify null handling in MapStruct", "test enum value mapping", or "check the round trip keeps all fields". Not for integration tests with a live database, end-to-end API tests, or writing the mapper implementations themselves. ---
Mapper and converter unit tests
Read the contract before writing a test
Collect: every mapper method signature, @Mapping/@ValueMapping annotations and expressions, source and target types, the configured null strategy, and the component model. Identify intended information loss, type conversions, timezones, collection ownership, and update semantics. Tests should assert observable transformations — never implementation class names.
Wiring rules:
- A standalone generated mapper with no injected dependencies instantiates with
Mappers.getMapper(UserMapper.class).
- A Spring-component mapper that injects other mappers needs real constructor
wiring or a small context; the standalone factory does not inject Spring beans.
- Confirm MapStruct plus its annotation processor are configured for the
project's build tool before assuming generated classes exist.
<dependency><groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId></dependency> <annotationProcessorPath><groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId></annotationProcessorPath>
Gradle equivalent: implementation("org.mapstruct:mapstruct") plus annotationProcessor("org.mapstruct:mapstruct-processor"), with JUnit Jupiter and AssertJ as test dependencies. Use the versions the project already pins.
Coverage matrix per mapping direction
| Contract point | Cases to assert | |---|---| | Simple / renamed fields | Distinct fixture values for every meaningful output | | Null input, nullable fields | The configured null or default behavior, not what you hope | | Collections | Empty, null, ordering, several distinct elements, mutability policy | | Nested objects | Populated and null independently and together; aliasing | | Expression / conversion | Boundary inputs, invalid input, exception policy | | Enums | Every declared @ValueMapping, plus the null/fallback policy | | Round trip | Fields preserved; document each intentional loss | | @MappingTarget update | Updated values, ignored fields, null and default semantics |
Use distinct values per field so swapped assignments cannot hide. For deep structures, prefer usingRecursiveComparison() and document excluded or generated fields instead of ignoring differences blindly. Bidirectional APIs are not automatically symmetric — a DTO may deliberately omit internal identity or computed fields.
Worked mapper test
For an equipment-rental mapper: assetCode becomes displayCode, manufacturer data maps independently, and an unavailable inventory status becomes the agreed external status.
class RentalItemMapperTest {
private final RentalItemMapper mapper = Mappers.getMapper(RentalItemMapper.class);
@Test
void mapsRenamedAndNestedFields() {
var item = new RentalItem(7L, "EQ-118", "DeWalt", "D25810K");
var dto = mapper.toDto(item);
assertThat(dto.getDisplayCode()).isEqualTo("EQ-118");
assertThat(dto.getBrand()).isEqualTo("DeWalt");
assertThat(dto.getModel()).isEqualTo("D25810K");
}
@Test
void mapsNullEntityToNull() {
assertThat(mapper.toDto(null)).isNull();
}
@Test
void mapsEveryEnumValue() {
assertThat(mapper.toExternalStatus(StockStatus.RETIRED))
.isEqualTo(ExternalStatus.UNAVAILABLE);
}
@Test
void mapsListsInOrder() {
var dtos = mapper.toDtos(List.of(item("EQ-1"), item("EQ-2")));
assertThat(dtos).extracting(RentalItemDto::getDisplayCode)
.containsExactly("EQ-1", "EQ-2");
}
}Round trip: convert entity → DTO → entity and assert preserved fields with usingRecursiveComparison(); list each field that is intentionally not restored. Partial update: call mapper.updateEntity(existing, dto) with a @MappingTarget method, then assert the changed fields *and* that identity and ownership fields survived. Null-preservation on updates only holds when the configured nullValuePropertyMappingStrategy says so — a primitive zero is not the same as an omitted value.
Custom converters: test null and invalid input directly
Real tests call the production converter; the snippet below just demonstrates the contract shape (round trip, null pass-through, rejection of malformed input) with only the standard library:
static String encode(LocalDate d) { return d == null ? null : d.toString(); }
static LocalDate decode(String s) { return s == null ? null : LocalDate.parse(s); }
LocalDate leapDay = LocalDate.of(2028, 2, 29);
assertThat(decode(encode(leapDay))).isEqualTo(leapDay);
assertThat(encode(null)).isNull();
assertThatThrownBy(() -> decode("2028-02-31"))
.isInstanceOf(DateTimeParseException.class);For JUnit tests use assertThat for values and assertThatThrownBy for exceptions. Money conversions need declared precision and rounding; date-time conversions must distinguish date-only values from instant-with-zone transitions. Avoid exact floating-point equality where approximate arithmetic is intentional.
Diagnosing generation and mapping failures
| Symptom | Where to look | |---|---| | Compile fails on generated sources | Expressions are not semantically validated by MapStruct; the generated Java is what fails | | Unexpected nulls | Check nullValuePropertyMappingStrategy, propertyMappingStrategy, nullValueCheckStrategy | | Nested object maps to null | A nested mapper method is missing or not wired into the parent mapper | | Enum mapping fails | The actual @ValueMapping set does not cover the value | | Circular object graphs | Needs a deliberate cycle strategy; assess the specific mappers, do not declare all cycles impossible |
With approval, compile and run the affected tests using the project's installed processor and framework versions. Then report: generation/build failures separately from assertion failures, methods and cases tested, missing tooling, and any transformations still uncovered.
Never
- Edit test files, generate annotation-processor output, install dependencies,
or run builds without confirmation of that exact action.
- Reimplement the converter inside the test and call the copy coverage.
- Assume Spring wiring, a null-ignore policy, or reverse symmetry without
reading the configuration.
- Skip null inputs, empty collections, invalid values, or timezone boundaries.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 7.0 kB | 31c114302a95 |
| examples.json | 2.3 kB | 7a8001a47c1e |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.1 Current | Not recorded | 6 Oct 2026 | |
| 1.0.0 | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.