[BAEL-5976]: Extract Values using AssertJ in Java (#13105)

JIRA: https://jira.baeldung.com/browse/BAEL-5976
This commit is contained in:
Carlos Chacin 2022-12-13 16:55:12 -08:00 committed by GitHub
parent abd9f8a38b
commit 78124d60dd
4 changed files with 109 additions and 0 deletions

View File

@ -0,0 +1,25 @@
package com.baeldung.assertj.extracting;
class Address {
private String street;
private String city;
private ZipCode zipCode;
Address(String street, String city, ZipCode zipCode) {
this.street = street;
this.city = city;
this.zipCode = zipCode;
}
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public ZipCode getZipCode() {
return zipCode;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.assertj.extracting;
class Person {
private String firstName;
private String lastName;
private Address address;
Person(String firstName, String lastName, Address address) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Address getAddress() {
return address;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.assertj.extracting;
class ZipCode {
private long zipcode;
ZipCode(long zipcode) {
this.zipcode = zipcode;
}
public long getZipcode() {
return zipcode;
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.assertj.extracting;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.as;
import static org.assertj.core.api.Assertions.assertThat;
class AssertJExtractingUnitTest {
static final List<Address> RESTRICTED_ADDRESSES = new ArrayList<>();
@Test
void whenUsingRegularAssertionFlow_thenCorrect() {
// Given
Person person = new Person("aName", "aLastName", new Address("aStreet", "aCity", new ZipCode(90210)));
// Then
Address address = person.getAddress();
assertThat(address).isNotNull()
.isNotIn(RESTRICTED_ADDRESSES);
ZipCode zipCode = address.getZipCode();
assertThat(zipCode).isNotNull();
assertThat(zipCode.getZipcode()).isBetween(1000L, 100_000L);
}
@Test
void whenUsingExtractingAssertionFlow_thenCorrect() {
// Given
Person person = new Person("aName", "aLastName", new Address("aStreet", "aCity", new ZipCode(90210)));
// Then
assertThat(person)
.extracting(Person::getAddress)
.isNotNull()
.isNotIn(RESTRICTED_ADDRESSES)
.extracting(Address::getZipCode)
.isNotNull()
.extracting(ZipCode::getZipcode, as(InstanceOfAssertFactories.LONG))
.isBetween(1_000L, 100_000L);
}
}