
Unit Test Mapper Converter
- 1.6k installs
- 311 repo stars
- Updated June 22, 2026
- giuseppe-trisciuoglio/developer-kit
Executable patterns for unit testing MapStruct mappers and custom converters to validate entity-to-DTO and model transformation logic.
About
Provides patterns and executable examples for unit testing MapStruct mappers, custom converters, and bean mappings. Developers use this when validating entity-to-DTO and model transformation logic in isolation, covering field mapping accuracy, null handling, type conversions, nested object transformations, bidirectional mapping, enum mapping, and partial updates. Key workflows include verifying generated mapper classes exist post-compilation, testing null handling with nullValueMappingStrategy configuration, validating bidirectional mappings via round-trip assertions, testing nested and collection transformations, and exhaustively testing enum value mappings. Best practices emphasize using recursive comparison for complex structures and keeping tests focused on transformation correctness.
- Verify generated MapStruct mapper classes exist in target/generated-sources or build/generated/sources before testing
- Test null handling with nullValueMappingStrategy and nullValuePropertyMappingStrategy configuration
- Validate bidirectional mapping using round-trip assertions (entity→DTO→entity equality checks)
- Test nested object and collection mappings with recursive comparison for complex structures
- Exhaustively test enum value mappings with @ValueMapping and validate custom expression syntax at runtime
Unit Test Mapper Converter by the numbers
- 1,634 all-time installs (skills.sh)
- +56 installs in the week ending Jul 28, 2026 (Skillselion tracking)
- Ranked #444 of 2,184 Testing & QA skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
unit-test-mapper-converter capabilities & compatibility
- Capabilities
- generate executable mapping test examples · validate null handling configurations for mapper · test nested object and collection transformation · verify bidirectional mapping consistency · test enum value mappings exhaustively · validate custom expression syntax at runtime
- Use cases
- testing · code review
- Platforms
- macOS · Windows · Linux
- Runs
- Runs locally
- Pricing
- Free
What unit-test-mapper-converter says it does
Provides patterns for unit testing MapStruct mappers and custom converter classes. Covers field mapping accuracy, null handling, type conversions, nested object transformations, bidirectional mapping,
Use when writing mapping tests, converter tests, entity mapping tests, or ensuring correct data transformation between DTOs and domain objects.
Test bidirectional mapping catches asymmetries between entity→DTO and DTO→entity
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill unit-test-mapper-converterAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.6k |
|---|---|
| repo stars | ★ 311 |
| Security audit | 3 / 3 scanners passed |
| Last updated | June 22, 2026 |
| Repository | giuseppe-trisciuoglio/developer-kit ↗ |
What it does
Write unit tests for MapStruct mappers and custom converters to validate entity-to-DTO transformations.
Who is it for?
Backend developers writing mapping layer tests for entity-to-DTO converters and MapStruct mapper implementations in Java applications.
Skip if: Frontend developers, web design, non-Java backend frameworks, or teams not using MapStruct or custom converter patterns.
When should I use this skill?
Writing mapping tests, testing custom converters, validating entity mapping, ensuring data transformation correctness between DTOs and domain objects.
What you get
Comprehensive unit tests for all mapping scenarios (null handling, nested objects, enums, bidirectional mappings, custom expressions) with MapStruct best practices.
- Unit test classes covering all mapping scenarios
- Null handling validation tests
- Bidirectional mapping round-trip tests
By the numbers
- Covers 6 key mapping scenarios: null handling, bidirectional mapping, nested objects, collections, enum mappings, and cu
- Includes complete executable test example with 3 test methods (toDto, roundTrip, null handling)
Files
Unit Testing Mappers and Converters
Overview
Provides patterns for unit testing MapStruct mappers and custom converter classes. Covers field mapping accuracy, null handling, type conversions, nested object transformations, bidirectional mapping, enum mapping, and partial updates.
When to Use
- Writing mapping tests for MapStruct mapper implementations
- Testing custom entity-to-DTO converters and bean mappings
- Validating nested object mapping and collection transformations
Instructions
1. Validate Generated Mapper Classes
Before testing, verify generated mapper classes exist:
# Maven
ls target/generated-sources/
# Gradle
ls build/generated/sources/If generated classes are missing: 1. Run mvn compile (Maven) or ./gradlew compileJava (Gradle) 2. Check that the MapStruct annotation processor is configured 3. Verify @Mapper interfaces are in a compiled source set
2. Test Null Handling
assertThat(mapper.toDto(null)).isNull();Configure nullValueMappingStrategy in mapper if null should return empty/default.
If null tests fail: 1. Add nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL to @Mapper 2. Or use nullValuePropertyMappingStrategy for nested property handling
3. Test Bidirectional Mapping
User restored = mapper.toEntity(mapper.toDto(original));
assertThat(restored).usingRecursiveComparison().isEqualTo(original);If bidirectional tests fail: 1. Check @Mapping annotations for field name mismatches 2. Verify both directions are explicitly mapped if auto-mapping fails 3. Use unmappedTargetPolicy = ReportingPolicy.ERROR to catch missing mappings
4. Test Nested Object Mapping
assertThat(dto.getNested()).usingRecursiveComparison().isEqualTo(expected);If nested tests fail: 1. Ensure nested mapper exists or is referenced via uses = NestedMapper.class 2. Check collection element mappings with elementMappingStrategy
5. Test Custom Expressions
Custom expressions in @Mapping(target = "field", expression = "java(...)") are not compile-time validated.
If expression tests fail: 1. Verify the expression syntax and method signatures 2. Check that imported classes are accessible from the expression context
6. Test Enum Mappings
Use @ValueMapping for enum-to-enum translations. Test all enum values exhaustively.
Best Practices
- Use
Mappers.getMapper()for standalone tests, Spring injection for integration tests - Use
usingRecursiveComparison()for complex nested structures - Test all mapper methods including collection transformations
- Verify null handling for all nullable source fields
- Test bidirectional mapping catches asymmetries between entity→DTO and DTO→entity
- Keep mapper tests focused on transformation correctness, not implementation details
Constraints and Warnings
- Compile-time generation: MapStruct generates code at compile time—verify generated classes exist before running tests
- Null handling: Configure
nullValueMappingStrategyandnullValuePropertyMappingStrategyappropriately - Expression validation: Expressions in
@Mappingare not validated at compile time—test them explicitly - Circular dependencies: MapStruct cannot handle circular dependencies between mappers
- Collection immutability: Mapping immutable collections may require special configuration
- Date/Time: Verify date/time objects map correctly across timezones
Examples
Complete executable test with imports:
package com.example.mapper;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import static org.assertj.core.api.Assertions.*;
class UserMapperCompleteTest {
private final UserMapper mapper = Mappers.getMapper(UserMapper.class);
@Test
void shouldMapUserToDto() {
User user = new User(1L, "Alice", "alice@example.com", 25);
UserDto dto = mapper.toDto(user);
assertThat(dto)
.isNotNull()
.extracting(UserDto::getName, UserDto::getEmail)
.containsExactly("Alice", "alice@example.com");
}
@Test
void shouldMaintainRoundTrip() {
User original = new User(1L, "Alice", "alice@example.com", 25);
assertThat(mapper.toEntity(mapper.toDto(original)))
.usingRecursiveComparison()
.isEqualTo(original);
}
@Test
void shouldHandleNullInput() {
assertThat(mapper.toDto(null)).isNull();
}
}Additional examples in: references/examples.md
Mapper & Converter Test Examples
Setup
Maven
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.5.Final</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>Gradle
dependencies {
implementation("org.mapstruct:mapstruct:1.5.5.Final")
testImplementation("org.junit.jupiter:junit-jupiter")
testImplementation("org.assertj:assertj-core")
}Basic Pattern: MapStruct Mapper
@Mapper(componentModel = "spring")
public interface UserMapper {
UserDto toDto(User user);
User toEntity(UserDto dto);
List<UserDto> toDtos(List<User> users);
}
class UserMapperTest {
private final UserMapper userMapper = Mappers.getMapper(UserMapper.class);
@Test
void shouldMapUserToDto() {
User user = new User(1L, "Alice", "alice@example.com", 25);
UserDto dto = userMapper.toDto(user);
assertThat(dto)
.isNotNull()
.extracting("id", "name", "email", "age")
.containsExactly(1L, "Alice", "alice@example.com", 25);
}
@Test
void shouldMapDtoToEntity() {
UserDto dto = new UserDto(1L, "Alice", "alice@example.com", 25);
User user = userMapper.toEntity(dto);
assertThat(user)
.isNotNull()
.hasFieldOrPropertyWithValue("id", 1L)
.hasFieldOrPropertyWithValue("name", "Alice");
}
@Test
void shouldMapListOfUsers() {
List<User> users = List.of(
new User(1L, "Alice", "alice@example.com", 25),
new User(2L, "Bob", "bob@example.com", 30)
);
List<UserDto> dtos = userMapper.toDtos(users);
assertThat(dtos)
.hasSize(2)
.extracting(UserDto::getName)
.containsExactly("Alice", "Bob");
}
@Test
void shouldHandleNullEntity() {
assertThat(userMapper.toDto(null)).isNull();
}
}Nested Object Mapping
class User {
private Long id;
private String name;
private Address address;
private List<Phone> phones;
}
class NestedObjectMapperTest {
private final UserMapper userMapper = Mappers.getMapper(UserMapper.class);
@Test
void shouldMapNestedAddress() {
Address address = new Address("123 Main St", "New York", "NY", "10001");
User user = new User(1L, "Alice", address);
UserDto dto = userMapper.toDto(user);
assertThat(dto.getAddress())
.isNotNull()
.hasFieldOrPropertyWithValue("street", "123 Main St");
}
@Test
void shouldMapListOfNestedPhones() {
List<Phone> phones = List.of(
new Phone("123-456-7890", "MOBILE"),
new Phone("987-654-3210", "HOME")
);
User user = new User(1L, "Alice", null, phones);
UserDto dto = userMapper.toDto(user);
assertThat(dto.getPhones())
.hasSize(2)
.extracting(PhoneDto::getNumber)
.containsExactly("123-456-7890", "987-654-3210");
}
@Test
void shouldHandleNullNestedObjects() {
User user = new User(1L, "Alice", null);
assertThat(userMapper.toDto(user).getAddress()).isNull();
}
}Custom Mapping Methods
@Mapper(componentModel = "spring")
public interface ProductMapper {
@Mapping(source = "name", target = "productName")
@Mapping(source = "price", target = "salePrice")
@Mapping(target = "discount", expression = "java(product.getPrice() * 0.1)")
ProductDto toDto(Product product);
}
class CustomMappingTest {
private final ProductMapper mapper = Mappers.getMapper(ProductMapper.class);
@Test
void shouldMapFieldsWithCustomNames() {
Product product = new Product(1L, "Laptop", 999.99);
ProductDto dto = mapper.toDto(product);
assertThat(dto)
.hasFieldOrPropertyWithValue("productName", "Laptop")
.hasFieldOrPropertyWithValue("salePrice", 999.99);
}
@Test
void shouldCalculateDiscountFromExpression() {
Product product = new Product(1L, "Laptop", 100.0);
ProductDto dto = mapper.toDto(product);
assertThat(dto.getDiscount()).isEqualTo(10.0);
}
}Enum Mapping
enum UserStatus { ACTIVE, INACTIVE, SUSPENDED }
enum UserStatusDto { ENABLED, DISABLED, LOCKED }
@Mapper(componentModel = "spring")
public interface StatusMapper {
@ValueMapping(source = "ACTIVE", target = "ENABLED")
@ValueMapping(source = "INACTIVE", target = "DISABLED")
@ValueMapping(source = "SUSPENDED", target = "LOCKED")
UserStatusDto toStatusDto(UserStatus status);
}
class EnumMapperTest {
private final StatusMapper mapper = Mappers.getMapper(StatusMapper.class);
@Test
void shouldMapActiveToEnabled() {
assertThat(mapper.toStatusDto(UserStatus.ACTIVE)).isEqualTo(UserStatusDto.ENABLED);
}
@Test
void shouldMapAllEnumValues() {
for (UserStatus status : UserStatus.values()) {
assertThat(mapper.toStatusDto(status)).isNotNull();
}
}
}Custom Type Converter
public class DateFormatter {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static String format(LocalDate date) {
return date != null ? date.format(formatter) : null;
}
public static LocalDate parse(String dateString) {
return dateString != null ? LocalDate.parse(dateString, formatter) : null;
}
}
class DateFormatterTest {
@Test
void shouldFormatLocalDateToString() {
assertThat(DateFormatter.format(LocalDate.of(2024, 1, 15))).isEqualTo("2024-01-15");
}
@Test
void shouldParseStringToLocalDate() {
assertThat(DateFormatter.parse("2024-01-15")).isEqualTo(LocalDate.of(2024, 1, 15));
}
@Test
void shouldHandleNullInFormat() {
assertThat(DateFormatter.format(null)).isNull();
}
@Test
void shouldThrowOnInvalidDateFormat() {
assertThatThrownBy(() -> DateFormatter.parse("invalid-date"))
.isInstanceOf(DateTimeParseException.class);
}
}Bidirectional Mapping (Round Trip)
class BidirectionalMapperTest {
private final UserMapper mapper = Mappers.getMapper(UserMapper.class);
@Test
void shouldMaintainDataInRoundTrip() {
User original = new User(1L, "Alice", "alice@example.com", 25);
UserDto dto = mapper.toDto(original);
User restored = mapper.toEntity(dto);
assertThat(restored)
.hasFieldOrPropertyWithValue("id", original.getId())
.hasFieldOrPropertyWithValue("name", original.getName());
}
@Test
void shouldPreserveAllFieldsInBothDirections() {
Address address = new Address("123 Main", "NYC", "NY", "10001");
User user = new User(1L, "Alice", "alice@example.com", 25, address);
UserDto dto = mapper.toDto(user);
User restored = mapper.toEntity(dto);
assertThat(restored).usingRecursiveComparison().isEqualTo(user);
}
}Partial Mapping (Update)
@Mapper(componentModel = "spring")
public interface UserMapper {
void updateEntity(@MappingTarget User entity, UserDto dto);
}
class PartialMapperTest {
private final UserMapper mapper = Mappers.getMapper(UserMapper.class);
@Test
void shouldUpdateExistingEntity() {
User existing = new User(1L, "Alice", "alice@old.com", 25);
UserDto dto = new UserDto(1L, "Alice", "alice@new.com", 26);
mapper.updateEntity(existing, dto);
assertThat(existing)
.hasFieldOrPropertyWithValue("email", "alice@new.com")
.hasFieldOrPropertyWithValue("age", 26);
}
@Test
void shouldNotUpdateFieldsNotInDto() {
User existing = new User(1L, "Alice", "alice@example.com", 25);
UserDto dto = new UserDto(1L, "Bob", null, 0);
mapper.updateEntity(existing, dto);
assertThat(existing.getEmail()).isEqualTo("alice@example.com");
}
}Related skills
Forks & variants (1)
Unit Test Mapper Converter has 1 known copy in the catalog totaling 21 installs. They canonicalize to this original listing.
- giuseppe-trisciuoglio - 21 installs
How it compares
Use unit-test-mapper-converter for focused MapStruct and converter unit tests; prefer integration tests when mapping depends on Spring context binding or external services.
FAQ
Why are my MapStruct generated mapper classes missing?
Run mvn compile or ./gradlew compileJava to trigger annotation processor, verify @Mapper interfaces exist in compiled source set, and confirm MapStruct annotation processor is configured in build.
How do I test that null inputs are handled correctly?
Use assertThat(mapper.toDto(null)).isNull(), and configure nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL in @Mapper if null should return non-null default.
How do I verify bidirectional mapping (entity→DTO→entity) consistency?
Assert round-trip equality using usingRecursiveComparison(): mapper.toEntity(mapper.toDto(original)) should equal original, catching asymmetries between directions.
Is Unit Test Mapper Converter safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.