Skip to content

Instantly share code, notes, and snippets.

@chhsiao90
Created June 6, 2017 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chhsiao90/15324ed3933b51c5f9e230af177c8af2 to your computer and use it in GitHub Desktop.
Save chhsiao90/15324ed3933b51c5f9e230af177c8af2 to your computer and use it in GitHub Desktop.
ModelMapper CollectionForConverterTest
package org.modelmapper.functional.iterable;
import static org.testng.Assert.assertEquals;
import org.modelmapper.AbstractTest;
import org.modelmapper.Converter;
import org.modelmapper.PropertyMap;
import org.modelmapper.spi.MappingContext;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Test
public class CollectionForConverterTest extends AbstractTest {
static class B1 {
private String foo;
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
static class B2 {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
static class Source {
private List<B1> prop;
public List<B1> getProp() {
return prop;
}
public void setProp(List<B1> prop) {
this.prop = prop;
}
}
static class Destination {
private List<B2> props;
public List<B2> getProps() {
return props;
}
public void setProps(List<B2> props) {
this.props = props;
}
}
@BeforeMethod
public void setUp() {
modelMapper.addConverter(new Converter<B1, B2>() {
public B2 convert(MappingContext<B1, B2> context) {
B2 b2 = new B2();
b2.setBar(context.getSource().getFoo());
return b2;
}
});
modelMapper.addMappings(new PropertyMap<Source, Destination>() {
protected void configure() {
map(source.getProp(), destination.getProps());
}
});
}
public void shouldMapOneItem() {
Source source = new Source();
source.setProp(Collections.singletonList(b1("foo")));
Destination destination = modelMapper.map(source, Destination.class);
assertEquals(destination.getProps().size(), 1);
assertEquals(destination.getProps().get(0).getBar(), "foo");
}
public void shouldMapItems() {
Source source = new Source();
source.setProp(Arrays.asList(b1("value1"), b1("value2")));
Destination destination = modelMapper.map(source, Destination.class);
assertEquals(destination.getProps().size(), 2);
assertEquals(destination.getProps().get(0).getBar(), "value1");
assertEquals(destination.getProps().get(1).getBar(), "value2");
}
private static B1 b1(String value) {
B1 b1 = new B1();
b1.setFoo(value);
return b1;
}
private static B2 b2(String value) {
B2 b2 = new B2();
b2.setBar(value);
return b2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment