Adds after / before mapping example (#7518)

This commit is contained in:
Nivedan Bamal 2019-08-08 01:38:03 -04:00 committed by Grzegorz Piwowarek
parent 69fb214962
commit 7f7fd337a7
6 changed files with 88 additions and 0 deletions

View File

@ -8,4 +8,5 @@ import lombok.Setter;
public class CarDTO {
private int id;
private String name;
private FuelType fuelType;
}

View File

@ -0,0 +1,5 @@
package com.baeldung.dto;
public enum FuelType {
ELECTRIC, BIO_DIESEL
}

View File

@ -0,0 +1,4 @@
package com.baeldung.entity;
public class BioDieselCar extends Car {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.entity;
public class ElectricCar extends Car {
}

View File

@ -0,0 +1,32 @@
package com.baeldung.mapper;
import org.mapstruct.AfterMapping;
import org.mapstruct.BeforeMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import com.baeldung.dto.CarDTO;
import com.baeldung.dto.FuelType;
import com.baeldung.entity.BioDieselCar;
import com.baeldung.entity.Car;
import com.baeldung.entity.ElectricCar;
@Mapper
public abstract class CarsMapper {
@BeforeMapping
protected void enrichDTOWithFuelType(Car car, @MappingTarget CarDTO carDto) {
if (car instanceof ElectricCar)
carDto.setFuelType(FuelType.ELECTRIC);
if (car instanceof BioDieselCar)
carDto.setFuelType(FuelType.BIO_DIESEL);
}
@AfterMapping
protected void convertNameToUpperCase(@MappingTarget CarDTO carDto) {
carDto.setName(carDto.getName().toUpperCase());
}
public abstract CarDTO toCarDto(Car car);
}

View File

@ -0,0 +1,42 @@
package com.baeldung.mapper;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.baeldung.dto.CarDTO;
import com.baeldung.dto.FuelType;
import com.baeldung.entity.BioDieselCar;
import com.baeldung.entity.Car;
import com.baeldung.entity.ElectricCar;
class CarsMapperUnitTest {
private CarsMapper sut = Mappers.getMapper(CarsMapper.class);
@Test
void testGivenSubTypeElectric_mapsModifiedFieldsToSuperTypeDto_whenBeforeAndAfterMappingMethodscarCalled() {
Car car = new ElectricCar();
car.setId(12);
car.setName("Tesla_Model_C");
CarDTO carDto = sut.toCarDto(car);
assertEquals("TESLA_MODEL_C", carDto.getName());
assertEquals(FuelType.ELECTRIC, carDto.getFuelType());
}
@Test
void testGivenSubTypeBioDiesel_mapsModifiedFieldsToSuperTypeDto_whenBeforeAndAfterMappingMethodscarCalled() {
Car car = new BioDieselCar();
car.setId(11);
car.setName("Tesla_Model_X");
CarDTO carDto = sut.toCarDto(car);
assertEquals("TESLA_MODEL_X", carDto.getName());
assertEquals(FuelType.BIO_DIESEL, carDto.getFuelType());
}
}