|
| 1 | +package com.baeldung.copyproperties; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | +import org.springframework.beans.BeanUtils; |
| 5 | + |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.HashSet; |
| 8 | + |
| 9 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 10 | +import static org.junit.jupiter.api.Assertions.assertNull; |
| 11 | + |
| 12 | +public class BeanUtilsCopyPropertiesUnitTest { |
| 13 | + |
| 14 | + @Test |
| 15 | + public void givenObjects_whenUsingIgnoreProperties_thenCopyProperties() { |
| 16 | + SourceBean sourceBean = new SourceBean("Peter", 30, "LA"); |
| 17 | + TargetBean targetBean = new TargetBean(); |
| 18 | + |
| 19 | + BeanUtils.copyProperties(sourceBean, targetBean, "address"); |
| 20 | + assertEquals(targetBean.getName(), sourceBean.getName()); |
| 21 | + assertEquals(targetBean.getAge(), sourceBean.getAge()); |
| 22 | + assertNull(targetBean.getAddress()); |
| 23 | + } |
| 24 | + |
| 25 | + @Test |
| 26 | + public void givenObjects_whenUsingIntermediateObject_thenCopyProperties() { |
| 27 | + SourceBean sourceBean = new SourceBean("Peter", 30, "LA"); |
| 28 | + TempDTO tempDTO = new TempDTO(); |
| 29 | + BeanUtils.copyProperties(sourceBean, tempDTO); |
| 30 | + |
| 31 | + TargetBean targetBean = new TargetBean(); |
| 32 | + BeanUtils.copyProperties(tempDTO, targetBean); |
| 33 | + assertEquals(targetBean.getName(), sourceBean.getName()); |
| 34 | + assertEquals(targetBean.getAge(), sourceBean.getAge()); |
| 35 | + assertNull(targetBean.getAddress()); |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + public void givenObjects_whenUsingCustomWrapper_thenCopyProperties() { |
| 40 | + SourceBean sourceBean = new SourceBean("Peter", 30, "LA"); |
| 41 | + TargetBean targetBean = new TargetBean(); |
| 42 | + BeanUtilsCopyProperties.copySelectedPropertiesUsingCustomWrapper(sourceBean, targetBean, new HashSet<>(Arrays.asList("name", "age"))); |
| 43 | + System.out.println(targetBean); |
| 44 | + assertEquals(targetBean.getName(), sourceBean.getName()); |
| 45 | + assertEquals(targetBean.getAge(), sourceBean.getAge()); |
| 46 | + assertNull(targetBean.getAddress()); |
| 47 | + } |
| 48 | +} |
0 commit comments