<properties> <org.mapstruct.version>1.3.0.Final</org.mapstruct.version> </properties> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>${org.mapstruct.version}</version> </dependency> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <!-- or newer version --> <configuration> <source>1.8</source> <target>1.8</target> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </path> <!-- other annotation processors --> </annotationProcessorPaths> </configuration> </plugin>
Java
public class Car { private String make; private int numberOfSeats; private CarType type; public Car(String make, int numberOfSeats, CarType type) { super(); this.make = make; this.numberOfSeats = numberOfSeats; this.type = type; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } public int getNumberOfSeats() { return numberOfSeats; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } public CarType getType() { return type; } public void setType(CarType type) { this.type = type; } } public class CarDto { private String make; private int seatCount; private String type; public String getMake() { return make; } public void setMake(String make) { this.make = make; } public int getSeatCount() { return seatCount; } public void setSeatCount(int seatCount) { this.seatCount = seatCount; } public String getType() { return type; } public void setType(String type) { this.type = type; } } @Mapper public interface CarMapper { CarMapper INSTANCE = Mappers.getMapper( CarMapper.class ); @Mapping(source = "numberOfSeats", target = "seatCount") CarDto carToCarDto(Car car); } public enum CarType { SEDAN, HATCHBACK; }
Test case
import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class CarMapperTest { @BeforeEach void setUp() throws Exception { } @Test void test() { //given Car car = new Car( "Morris", 5, CarType.SEDAN ); //when CarDto carDto = CarMapper.INSTANCE.carToCarDto( car ); assertNotNull(carDto); assertThat(carDto.getMake(), is("Morris") ); assertThat(carDto.getSeatCount(), is(5)); assertThat(carDto.getType(), is("SEDAN")); } }
No comments:
Post a Comment