Java / MapStruct Java Interview questions part 2
How do you unit test a MapStruct-generated mapper?
Because a MapStruct mapper compiles down to plain Java with no runtime magic, testing it needs nothing beyond a normal JUnit test - no mocking framework or reflection tricks are required.
class CarMapperTest { private final CarMapper mapper = Mappers.getMapper(CarMapper.class); @Test void mapsCarToDto() { Car car = new Car("Model X", 2024); CarDto dto = mapper.carToCarDto(car); assertEquals("Model X", dto.getModel()); assertEquals(2024, dto.getYear()); } }
Because the mapper is generated at compile time, these tests double as a safety net for the mapping configuration itself - if a future @Mapping change accidentally breaks a property, the assertion catches it immediately rather than relying solely on the compiler warning being noticed.
More Related questions...