コード例 #1
0
  @Test
  public void shouldMapListElements() {
    // given
    MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();

    mapperFactory
        .classMap(BasicPerson.class, BasicPersonDto.class)
        .field("nameParts[0]", "firstName")
        .field("nameParts[1]", "lastName")
        .register();

    BasicPerson bp = new BasicPerson();
    bp.setNameParts(Lists.asList("Jan", new String[] {"Kowalski"}));

    // when
    MapperFacade mapperFacade = mapperFactory.getMapperFacade();
    BasicPersonDto result = mapperFacade.map(bp, BasicPersonDto.class);

    // then
    assertThat(result.getFirstName()).isEqualTo("Jan");
    assertThat(result.getLastName()).isEqualTo("Kowalski");
    assertThat(result.getBirthDate()).isNull();
    assertThat(result.getCurrentAge()).isEqualTo(0);
    assertThat(result.getFullName()).isNull();
  }
コード例 #2
0
  @Test
  public void shouldCustomizeMapping() {
    // given
    MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();

    mapperFactory
        .classMap(BasicPerson.class, BasicPersonDto.class)
        .field("age", "currentAge")
        .byDefault()
        .customize(
            new CustomMapper<BasicPerson, BasicPersonDto>() {
              @Override
              public void mapAtoB(
                  BasicPerson basicPerson, BasicPersonDto basicPersonDto, MappingContext context) {
                Joiner joiner = Joiner.on(" ");
                String fullName =
                    joiner
                        .appendTo(
                            new StringBuilder(basicPerson.getName()).append(" "),
                            basicPerson.getNameParts())
                        .toString();

                basicPersonDto.setFullName(fullName);
              }
            })
        .register();

    BasicPerson bp = createBasicPerson("Jan", 20, Calendar.getInstance().getTime());
    bp.setNameParts(Lists.asList("von", new String[] {"Kowalski"}));

    // when
    MapperFacade mapperFacade = mapperFactory.getMapperFacade();
    BasicPersonDto result = mapperFacade.map(bp, BasicPersonDto.class);

    // then
    assertThat(result.getFullName()).isEqualTo("Jan von Kowalski");
    assertThat(result.getCurrentAge()).isEqualTo(bp.getAge());
    assertThat(result.getBirthDate()).isNotNull();
  }