Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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()));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement