[BAEL-6623] Add code for Convert Object to String (#15000)

* Add Person class

* Add Unit tests for Person class

* Add Person class

* Add PersonWithHashCode class

* Address review comments

* Add PersonUnitTest class

* Add PersonWithHashCodeUnitTest class

* Add missing dependency

* Remove redundant code

* Remove redundant code

* Address review comments

* Address review comments
This commit is contained in:
anujgaud 2023-10-22 09:49:38 +05:30 committed by GitHub
parent b0ed62e8c8
commit 781a1c265a
3 changed files with 81 additions and 1 deletions

View File

@ -23,4 +23,12 @@
</resources> </resources>
</build> </build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project> </project>

View File

@ -0,0 +1,34 @@
package com.baeldung.objecttostring;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
public String toCustomString() {
return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
.append("name", name)
.append("age", age)
.toString();
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.objecttostring;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PersonUnitTest {
@Test
public void givenObject_whenToString_thenConvert() {
Person person = new Person("Sarah", 28);
String expected = "Person{name='Sarah', age=28}";
String actual = person.toString();
assertEquals(expected, actual);
}
@Test
public void givenObject_whenValueOf_thenConvert() {
Person person = new Person("Sarah", 28);
String expected = "Person{name='Sarah', age=28}";
String actual = String.valueOf(person);
assertEquals(expected, actual);
}
@Test
public void givenObject_whenConcat_thenConvert() {
Person person = new Person("Sarah", 28);
String expected = "Person{name='Sarah', age=28}";
String actual = "" + person;
assertEquals(expected, actual);
}
@Test
public void givenObject_whenToStringBuilder_thenConvert() {
Person person = new Person("Sarah", 28);
String expected = "{\"name\":\"Sarah\",\"age\":28}";
String actual = person.toCustomString();
assertEquals(expected, actual);
}
}