Merge pull request #15811 from Imranalam28/master

[BAEL-7501] Immutable and Mutable Object Examples with Tests
This commit is contained in:
Vini 2024-02-06 08:25:27 +01:00 committed by GitHub
commit bb998a3863
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 99 additions and 0 deletions

View File

@ -0,0 +1,21 @@
package com.baeldung.objectmutability;
public final class ImmutablePerson {
private final String name;
private final int age;
public ImmutablePerson(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.objectmutability;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
public class ImmutableObjectExamplesUnitTest {
@Test
public void givenImmutableString_whenConcatString_thenNotSameAndCorrectValues() {
String originalString = "Hello";
String modifiedString = originalString.concat(" World");
assertNotSame(originalString, modifiedString);
assertEquals("Hello", originalString);
assertEquals("Hello World", modifiedString);
}
@Test
public void givenImmutableInteger_whenAddInteger_thenNotSameAndCorrectValue() {
Integer immutableInt = 42;
Integer modifiedInt = immutableInt + 8;
assertNotSame(immutableInt, modifiedInt);
assertEquals(42, (int) immutableInt);
assertEquals(50, (int) modifiedInt);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.objectmutability;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ImmutablePersonUnitTest {
@Test
public void givenImmutablePerson_whenAccessFields_thenCorrectValues() {
ImmutablePerson person = new ImmutablePerson("John", 30);
assertEquals("John", person.getName());
assertEquals(30, person.getAge());
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.objectmutability;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MutableObjectExamplesUnitTest {
@Test
public void givenMutableString_whenAppendElement_thenCorrectValue() {
StringBuilder mutableString = new StringBuilder("Hello");
mutableString.append(" World");
assertEquals("Hello World", mutableString.toString());
}
@Test
public void givenMutableList_whenAddElement_thenCorrectSize() {
List<String> mutableList = new ArrayList<>();
mutableList.add("Java");
assertEquals(1, mutableList.size());
}
}