Skip to content

Instantly share code, notes, and snippets.

@amischler
Last active March 18, 2019 16:51
Show Gist options
  • Save amischler/876c928ac6f936c1df94609d6ef13a5b to your computer and use it in GitHub Desktop.
Save amischler/876c928ac6f936c1df94609d6ef13a5b to your computer and use it in GitHub Desktop.
public class ModelMapperReMappingTest {
interface Configurable {
void configure();
}
static class B1 {
String prop;
public String getProp() {
return prop;
}
public void setProp(String prop) {
this.prop = prop;
}
}
static class A1 {
private B1 b;
public B1 getB() {
return b;
}
public void setB(B1 b) {
this.b = b;
}
}
static class B2 implements Configurable {
String prop;
@Override
public void configure() {
System.out.println("Configuring");
}
public String getProp() {
return prop;
}
public void setProp(String prop) {
this.prop = prop;
}
}
static class A2 {
private B2 b;
public B2 getB() {
return b;
}
public void setB(B2 b) {
this.b = b;
}
}
class ConfigurableEntityProvider implements Provider<Object> {
@Override
public Object get(ProvisionRequest<Object> request) {
if (Configurable.class.isAssignableFrom(request.getRequestedType())) {
try {
Configurable entity = (Configurable) request.getRequestedType().newInstance();
entity.configure();
return entity;
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
}
} else {
return null;
}
}
}
@Test
public void testWithoutMapping() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setProvider(new ConfigurableEntityProvider());
A1 aSource = new A1();
B1 bSource = new B1();
bSource.setProp("value");
aSource.setB(bSource);
A2 target = modelMapper.map(aSource, A2.class);
B2 bTarget = target.getB();
Assert.assertEquals("value", target.getB().getProp());
bSource.setProp("value2");
modelMapper.map(aSource, target);
Assert.assertEquals("value2", target.getB().getProp());
Assert.assertEquals(System.identityHashCode(bTarget), System.identityHashCode(target.getB()));
}
@Test
public void testWithMapping() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.addMappings(new PropertyMap<A1, A2>() {
@Override
protected void configure() {
map(source.getB()).setB(null);
}
});
modelMapper.getConfiguration().setProvider(new ConfigurableEntityProvider());
A1 aSource = new A1();
B1 bSource = new B1();
bSource.setProp("value");
aSource.setB(bSource);
A2 target = modelMapper.map(aSource, A2.class);
B2 bTarget = target.getB();
Assert.assertEquals("value", target.getB().getProp());
bSource.setProp("value2");
modelMapper.map(aSource, target);
Assert.assertEquals("value2", target.getB().getProp());
Assert.assertEquals(System.identityHashCode(bTarget), System.identityHashCode(target.getB()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment