|
| 1 | +package com.baeldung.assertj; |
| 2 | + |
| 3 | +import com.baeldung.assertj.domain.Dog; |
| 4 | +import com.baeldung.assertj.domain.Person; |
| 5 | +import org.junit.Ignore; |
| 6 | +import org.junit.Test; |
| 7 | + |
| 8 | +import java.util.Arrays; |
| 9 | +import java.util.List; |
| 10 | +import java.util.NoSuchElementException; |
| 11 | + |
| 12 | +import static org.assertj.core.api.Assertions.assertThat; |
| 13 | +import static org.assertj.core.api.Assertions.withPrecision; |
| 14 | + |
| 15 | +public class AssertJDemoTest { |
| 16 | + |
| 17 | + @Test |
| 18 | + public void whenComparingReferences_thenNotEqual() throws Exception { |
| 19 | + Dog fido = new Dog("Fido", 5.15f); |
| 20 | + Dog fidosClone = new Dog("Fido", 5.15f); |
| 21 | + |
| 22 | + assertThat(fido).isNotEqualTo(fidosClone); |
| 23 | + } |
| 24 | + |
| 25 | + @Test |
| 26 | + public void whenComparingFields_thenEqual() throws Exception { |
| 27 | + Dog fido = new Dog("Fido", 5.15f); |
| 28 | + Dog fidosClone = new Dog("Fido", 5.15f); |
| 29 | + |
| 30 | + assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + public void whenCheckingForElement_thenContains() throws Exception { |
| 35 | + List<String> list = Arrays.asList("1", "2", "3"); |
| 36 | + |
| 37 | + assertThat(list) |
| 38 | + .contains("1"); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void whenCheckingForElement_thenMultipleAssertions() throws Exception { |
| 43 | + List<String> list = Arrays.asList("1", "2", "3"); |
| 44 | + |
| 45 | + assertThat(list) |
| 46 | + .isNotEmpty() |
| 47 | + .contains("1") |
| 48 | + .startsWith("1") |
| 49 | + .doesNotContainNull() |
| 50 | + .containsSequence("2", "3"); |
| 51 | + } |
| 52 | + |
| 53 | + @Test |
| 54 | + public void whenCheckingRunnable_thenIsInterface() throws Exception { |
| 55 | + assertThat(Runnable.class).isInterface(); |
| 56 | + } |
| 57 | + |
| 58 | + @Test |
| 59 | + public void whenAssigningNSEExToException_thenIsAssignable() throws Exception { |
| 60 | + assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class); |
| 61 | + } |
| 62 | + |
| 63 | + @Test |
| 64 | + public void whenComparingWithOffset_thenEquals() throws Exception { |
| 65 | + assertThat(5.1).isEqualTo(5, withPrecision(1d)); |
| 66 | + } |
| 67 | + |
| 68 | + @Ignore // IN ORDER TO TEST, REMOVE THIS LINE |
| 69 | + @Test |
| 70 | + public void whenRunningAssertion_thenDescribed() throws Exception { |
| 71 | + Person person = new Person("Alex", 34); |
| 72 | + |
| 73 | + assertThat(person.getAge()) |
| 74 | + .as("%s's age should be equal to 100") |
| 75 | + .isEqualTo(100); |
| 76 | + } |
| 77 | +} |
0 commit comments