Skip to content

Commit 85144ff

Browse files
Added assertj exception assertion snippet
1 parent c98e602 commit 85144ff

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# Java Testing Made Easy
22
This repository contains the sample code for **Java Testing Made Easy YouTube Tutorial Series**
33

4+
https://www.youtube.com/playlist?list=PLuNxlOYbv61jtHHFHBOc9N7Dg5jn013ix
5+
46
![java-testing-made-easy](assets/java-testing-made-easy.png)
57

junit5-assertj-sample/src/test/java/com/sivalabs/jtme/PersonServiceTest.java

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,12 @@
44
import org.junit.jupiter.api.Test;
55

66
import java.util.List;
7+
import java.util.UUID;
78

89
import static org.assertj.core.api.Assertions.assertThat;
10+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
11+
import static org.junit.jupiter.api.Assertions.assertThrows;
12+
import static org.junit.jupiter.api.Assertions.assertTrue;
913

1014
class PersonServiceTest {
1115

@@ -22,7 +26,26 @@ void shouldCreatePerson() {
2226
Person person = personService.create(new Person(null, "Siva", "siva@gmail.com"));
2327
assertThat(person.getId()).isNotNull();
2428
assertThat(person.getName()).isEqualTo("Siva");
25-
assertThat(person.getEmail()).isEqualTo("siva@gmail.com");
29+
assertThat(person.getEmail()).isEqualTo("siva@gmail.com").endsWith("@gmail.com");
30+
}
31+
32+
@Test
33+
void shouldThrowExceptionWhenCreatePersonWithDuplicateEmail() {
34+
String email = UUID.randomUUID().toString()+"@gmail.com";
35+
personService.create(new Person(null, "Siva", email));
36+
37+
//Junit 5 assertion
38+
RuntimeException exception = assertThrows(RuntimeException.class, () -> {
39+
personService.create(new Person(null, "Siva", email));
40+
});
41+
assertTrue(exception.getMessage()
42+
.contentEquals("Person with email '"+email+"' already exists"));
43+
44+
//Assertj assertion
45+
assertThatThrownBy(()-> {
46+
personService.create(new Person(null, "Siva", email));
47+
}).isInstanceOf(RuntimeException.class)
48+
.hasMessage("Person with email '"+email+"' already exists");
2649
}
2750

2851
@Test

0 commit comments

Comments
 (0)