├── .gitignore
├── README.md
├── S03_FirstStepsInJUnit5WithJava
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── br
│ │ └── com
│ │ └── erudio
│ │ └── math
│ │ └── SimpleMath.java
│ └── test
│ └── java
│ └── br
│ └── com
│ └── erudio
│ ├── ArraysCompareTest.java
│ ├── FooBarTest.java
│ └── math
│ └── SimpleMathTest.java
├── S04_AdvancedConceptsofJUnit5
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── br
│ │ └── com
│ │ └── erudio
│ │ └── math
│ │ └── SimpleMath.java
│ └── test
│ ├── java
│ └── br
│ │ └── com
│ │ └── erudio
│ │ ├── ArraysCompareTest.java
│ │ ├── FooBarTest.java
│ │ ├── MethodOrderedByNameTest.java
│ │ ├── MethodOrderedByOrderIndexTest.java
│ │ ├── MethodOrderedRandonlyTest.java
│ │ └── math
│ │ ├── DemoRepeatedTest.java
│ │ ├── SimpleMathTestS3.java
│ │ └── SimpleMathTestS4.java
│ └── resources
│ ├── junit-platform.properties
│ └── testDivision.csv
├── S05_JUnit5andTDD
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── br
│ │ └── com
│ │ └── erudio
│ │ ├── model
│ │ └── Person.java
│ │ └── service
│ │ ├── IPersonService.java
│ │ └── PersonService.java
│ └── test
│ └── java
│ └── br
│ └── com
│ └── erudio
│ └── PersonServiceTest.java
├── S06_MockitosFirstSteps
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── br
│ │ └── com
│ │ └── erudio
│ │ ├── business
│ │ └── CourseBusiness.java
│ │ └── service
│ │ └── CourseService.java
│ └── test
│ └── java
│ └── br
│ └── com
│ └── erudio
│ ├── business
│ ├── CourseBusinessMockTest.java
│ ├── CourseBusinessMockWithBDDTest.java
│ ├── CourseBusinessStubTest.java
│ ├── ListTest.java
│ └── ListWithBDDTest.java
│ └── service
│ └── stubs
│ └── CourseServiceStub.java
├── S07_AdvancedConceptsofMockito
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── br
│ │ └── com
│ │ └── erudio
│ │ ├── business
│ │ └── CourseBusiness.java
│ │ ├── mockito
│ │ ├── constructor
│ │ ├── services
│ │ │ ├── Order.java
│ │ │ └── OrderService.java
│ │ └── staticwithparams
│ │ │ └── MyUtils.java
│ │ └── service
│ │ └── CourseService.java
│ └── test
│ └── java
│ └── br
│ └── com
│ └── erudio
│ ├── business
│ ├── CourseBusinessMockTest.java
│ ├── CourseBusinessMockWithBDDTest.java
│ ├── CourseBusinessStubTest.java
│ ├── ListTest.java
│ └── ListWithBDDTest.java
│ ├── mockito
│ ├── CourseBusinessMockitoInjectMocksTest.java
│ ├── HamcrestMatchersTest.java
│ ├── SpyTest.java
│ ├── constructor
│ ├── services
│ │ └── OrderServiceTest.java
│ └── staticwithparams
│ │ └── MyUtilsTest.java
│ └── service
│ └── stubs
│ └── CourseServiceStub.java
├── S08_CodeCoverage
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── br
│ │ └── com
│ │ └── erudio
│ │ ├── business
│ │ └── CourseBusiness.java
│ │ ├── mockito
│ │ ├── constructor
│ │ ├── services
│ │ │ ├── Order.java
│ │ │ └── OrderService.java
│ │ └── staticwithparams
│ │ │ └── MyUtils.java
│ │ └── service
│ │ └── CourseService.java
│ └── test
│ └── java
│ └── br
│ └── com
│ └── erudio
│ ├── business
│ ├── CourseBusinessMockTest.java
│ ├── CourseBusinessMockWithBDDTest.java
│ ├── CourseBusinessStubTest.java
│ ├── ListTest.java
│ └── ListWithBDDTest.java
│ ├── mockito
│ ├── CourseBusinessMockitoInjectMocksTest.java
│ ├── HamcrestMatchersTest.java
│ ├── SpyTest.java
│ ├── constructor
│ ├── services
│ │ └── OrderServiceTest.java
│ └── staticwithparams
│ │ └── MyUtilsTest.java
│ └── service
│ └── stubs
│ └── CourseServiceStub.java
├── S09A_FirstStepsInJavawithSpringBoot
└── rest-with-spring-boot-and-java-erudio
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── br
│ │ │ └── com
│ │ │ └── erudio
│ │ │ ├── Greeting.java
│ │ │ ├── GreetingController.java
│ │ │ └── Startup.java
│ └── resources
│ │ └── application.yml
│ └── test
│ └── java
│ └── br
│ └── com
│ └── erudio
│ └── StartupTests.java
├── S09B_ParametersAndExceptionHandler
└── rest-with-spring-boot-and-java-erudio
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── br
│ │ │ └── com
│ │ │ └── erudio
│ │ │ ├── Startup.java
│ │ │ ├── controllers
│ │ │ └── MathController.java
│ │ │ ├── converters
│ │ │ └── NumberConverter.java
│ │ │ ├── exceptions
│ │ │ ├── ExceptionResponse.java
│ │ │ ├── UnsupportedMathOperationException.java
│ │ │ └── handler
│ │ │ │ └── CustomizedResponseEntityExceptionHandler.java
│ │ │ └── math
│ │ │ └── SimpleMath.java
│ └── resources
│ │ └── application.yml
│ └── test
│ └── java
│ └── br
│ └── com
│ └── erudio
│ └── StartupTests.java
├── S09C_WorkingWithVerbs
└── rest-with-spring-boot-and-java-erudio
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── br
│ │ │ └── com
│ │ │ └── erudio
│ │ │ ├── Startup.java
│ │ │ ├── controllers
│ │ │ └── PersonController.java
│ │ │ ├── exceptions
│ │ │ ├── ExceptionResponse.java
│ │ │ ├── UnsupportedMathOperationException.java
│ │ │ └── handler
│ │ │ │ └── CustomizedResponseEntityExceptionHandler.java
│ │ │ ├── model
│ │ │ └── Person.java
│ │ │ └── services
│ │ │ └── PersonServices.java
│ └── resources
│ │ └── application.yml
│ └── test
│ └── java
│ └── br
│ └── com
│ └── erudio
│ └── StartupTests.java
├── S09D_ConnectingToMySQL
└── rest-with-spring-boot-and-java-erudio
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── br
│ │ │ └── com
│ │ │ └── erudio
│ │ │ ├── Startup.java
│ │ │ ├── controllers
│ │ │ └── PersonController.java
│ │ │ ├── exceptions
│ │ │ ├── ExceptionResponse.java
│ │ │ ├── ResourceNotFoundException.java
│ │ │ └── handler
│ │ │ │ └── CustomizedResponseEntityExceptionHandler.java
│ │ │ ├── model
│ │ │ └── Person.java
│ │ │ ├── repositories
│ │ │ └── PersonRepository.java
│ │ │ └── services
│ │ │ └── PersonServices.java
│ └── resources
│ │ └── application.yml
│ └── test
│ └── java
│ └── br
│ └── com
│ └── erudio
│ └── StartupTests.java
├── S10_TestingRepositories
└── rest-with-spring-boot-and-java-erudio
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── br
│ │ │ └── com
│ │ │ └── erudio
│ │ │ ├── Startup.java
│ │ │ ├── controllers
│ │ │ └── PersonController.java
│ │ │ ├── exceptions
│ │ │ ├── ExceptionResponse.java
│ │ │ ├── ResourceNotFoundException.java
│ │ │ └── handler
│ │ │ │ └── CustomizedResponseEntityExceptionHandler.java
│ │ │ ├── model
│ │ │ └── Person.java
│ │ │ ├── repositories
│ │ │ └── PersonRepository.java
│ │ │ └── services
│ │ │ └── PersonServices.java
│ └── resources
│ │ └── application.yml
│ └── test
│ ├── java
│ └── br
│ │ └── com
│ │ └── erudio
│ │ ├── StartupTests.java
│ │ └── repositories
│ │ └── PersonRepositoryTest.java
│ └── resources
│ └── application.yml
├── S11_TestingServices
└── rest-with-spring-boot-and-java-erudio
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── br
│ │ │ └── com
│ │ │ └── erudio
│ │ │ ├── Startup.java
│ │ │ ├── controllers
│ │ │ └── PersonController.java
│ │ │ ├── exceptions
│ │ │ ├── ExceptionResponse.java
│ │ │ ├── ResourceNotFoundException.java
│ │ │ └── handler
│ │ │ │ └── CustomizedResponseEntityExceptionHandler.java
│ │ │ ├── model
│ │ │ └── Person.java
│ │ │ ├── repositories
│ │ │ └── PersonRepository.java
│ │ │ └── services
│ │ │ └── PersonServices.java
│ └── resources
│ │ └── application.yml
│ └── test
│ ├── java
│ └── br
│ │ └── com
│ │ └── erudio
│ │ ├── StartupTests.java
│ │ ├── repositories
│ │ └── PersonRepositoryTest.java
│ │ └── services
│ │ └── PersonServicesTest.java
│ └── resources
│ └── application.yml
├── S12_TestingControllers
└── rest-with-spring-boot-and-java-erudio
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── br
│ │ │ └── com
│ │ │ └── erudio
│ │ │ ├── Startup.java
│ │ │ ├── controllers
│ │ │ └── PersonController.java
│ │ │ ├── exceptions
│ │ │ ├── ExceptionResponse.java
│ │ │ ├── ResourceNotFoundException.java
│ │ │ └── handler
│ │ │ │ └── CustomizedResponseEntityExceptionHandler.java
│ │ │ ├── model
│ │ │ └── Person.java
│ │ │ ├── repositories
│ │ │ └── PersonRepository.java
│ │ │ └── services
│ │ │ └── PersonServices.java
│ └── resources
│ │ └── application.yml
│ └── test
│ ├── java
│ └── br
│ │ └── com
│ │ └── erudio
│ │ ├── StartupTests.java
│ │ ├── controllers
│ │ └── PersonControllerTest.java
│ │ ├── repositories
│ │ └── PersonRepositoryTest.java
│ │ └── services
│ │ └── PersonServicesTest.java
│ └── resources
│ └── application.yml
└── S13_IntegrationTests
└── rest-with-spring-boot-and-java-erudio
├── pom.xml
└── src
├── main
├── java
│ └── br
│ │ └── com
│ │ └── erudio
│ │ ├── Startup.java
│ │ ├── config
│ │ └── OpenAPIConfig.java
│ │ ├── controllers
│ │ └── PersonController.java
│ │ ├── exceptions
│ │ ├── ExceptionResponse.java
│ │ ├── ResourceNotFoundException.java
│ │ └── handler
│ │ │ └── CustomizedResponseEntityExceptionHandler.java
│ │ ├── model
│ │ └── Person.java
│ │ ├── repositories
│ │ └── PersonRepository.java
│ │ └── services
│ │ └── PersonServices.java
└── resources
│ └── application.yml
└── test
├── java
└── br
│ └── com
│ └── erudio
│ ├── config
│ └── TestConfigs.java
│ ├── controllers
│ └── PersonControllerTest.java
│ ├── integrationtests
│ ├── controller
│ │ └── PersonControllerIntegrationTest.java
│ ├── swagger
│ │ └── SwaggerIntegrationTest.java
│ └── testcontainers
│ │ └── AbstractIntegrationTest.java
│ ├── repositories
│ └── PersonRepositoryTest.java
│ └── services
│ └── PersonServicesTest.java
└── resources
└── application.yml
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 |
4 | /node_modules
5 |
6 | # SSH Keys
7 |
8 | *.pem
9 | *.ppk
10 |
11 | # Mobile Tools for Java (J2ME)
12 | .mtj.tmp/
13 |
14 | # Package Files #
15 | *.jar
16 | *.war
17 | *.ear
18 |
19 | # Merge Files
20 | *.bak
21 |
22 | #Gradle temporary files
23 | target/
24 |
25 | #Eclipse files
26 | **/.project
27 | **/.classpath
28 | **/.settings/
29 | /bin/
30 | blog/bin/
31 | **/.tern-project
32 | **/.factorypath
33 |
34 | #IntelliJ files
35 | **/*.iml
36 | **/.idea
37 | **/.gradle
38 |
39 | #Other Files
40 | *.ini
41 |
42 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
43 | hs_err_pid*
44 | /.metadata/
45 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # [Java Unit Testing com Spring Boot 3, Junit 5 e Mockito](https://www.udemy.com/course/restful-apis-do-0-a-nuvem-com-springboot-e-docker/?couponCode=GTHB_FLASH_SALE2021)
2 | ### [Domine Testes Unitários e de Integração para APPs Java e Spring Boot 3 com JUnit 5, Mockito, TestContainers, TDD e +++++](https://www.udemy.com/course/restful-apis-do-0-a-nuvem-com-springboot-e-docker/?couponCode=GTHB_FLASH_SALE2021)
3 |
4 | [](https://www.udemy.com/course/java-unit-testing-com-java-spring-boot-3-junit-5-e-mockito/?couponCode=GTHB_FLASH_SALE2021)
5 |
6 | Este é o repositório dos codigos fonte desenvolvidos no curso [Java Unit Testing com Spring Boot 3, TDD, Junit 5 e Mockito](https://www.udemy.com/course/java-unit-testing-com-java-spring-boot-3-junit-5-e-mockito/?couponCode=GTHB_FLASH_SALE2021)
7 |
8 | # Cursos Relacionados
9 |
10 | [](https://www.udemy.com/course/restful-apis-do-0-a-nuvem-com-springboot-e-docker/?couponCode=GTHB_FLASH_SALE2021)
11 |
12 | [](https://www.udemy.com/course/docker-do-zero-a-maestria-conteinerizacao-desmistificada/?couponCode=GTHB_FLASH_SALE2021)
13 |
14 | [](https://www.udemy.com/course/microservices-do-0-a-gcp-com-spring-boot-kubernetes-e-docker/?couponCode=GTHB_FLASH_SALE2021)
15 |
16 | [](https://www.udemy.com/course/restful-apis-do-0-a-nuvem-com-aspnet-core-e-docker/?couponCode=GTHB_FLASH_SALE2021)
17 |
18 | [](https://www.udemy.com/course/microservices-do-0-a-gcp-com-dot-net-6-kubernetes-e-docker/?couponCode=GTHB_FLASH_SALE2021)
19 |
20 | [](https://www.udemy.com/course/docker-para-amazon-aws-implante-aplicacoes-java-e-net/?couponCode=GTHB_FLASH_SALE2021)
21 |
22 | ## In English
23 |
24 | [](https://www.udemy.com/course/rest-apis-restful-from-0-to-aws-with-spring-boot-and-docker/?couponCode=GTHB_FLASH_SALE2021)
25 |
26 | [](https://www.udemy.com/course/docker-to-amazon-aws-deploy-java-net-apps-with-travis-ci/?couponCode=GTHB_FLASH_SALE2021)
27 |
28 | ## [Configuração do Ambiente de Desenvolvimento Spring Boot e Java no Windows](https://www.youtube.com/watch?v=sdY-N6nnyaE)
29 |
30 | [](https://www.youtube.com/watch?v=sdY-N6nnyaE)
31 |
32 | ## [Configuração do Ambiente de Desenvolvimento Spring Boot e Java no Linux (Ubuntu/Debian)](https://www.youtube.com/watch?v=dEszOKOR4Nk)
33 |
34 | [](https://www.youtube.com/watch?v=dEszOKOR4Nk)
35 |
--------------------------------------------------------------------------------
/S03_FirstStepsInJUnit5WithJava/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | br.com.erudio
4 | automated-tests-with-java-erudio
5 | 0.0.1-SNAPSHOT
6 |
7 | 19
8 | 5.9.2
9 | 19
10 | 19
11 | 3.10.1
12 |
13 |
14 |
15 |
16 | org.junit.jupiter
17 | junit-jupiter
18 | ${junit.version}
19 | test
20 |
21 |
22 |
23 |
24 |
25 |
26 | org.apache.maven.plugins
27 | maven-compiler-plugin
28 |
29 | ${java.version}
30 | ${java.version}
31 |
32 | ${maven.compiler.plugin.version}
33 |
34 |
35 | org.apache.maven.plugins
36 | maven-surefire-plugin
37 | 3.0.0-M9
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/S03_FirstStepsInJUnit5WithJava/src/main/java/br/com/erudio/math/SimpleMath.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.math;
2 |
3 | public class SimpleMath {
4 |
5 | public Double sum(Double firstNumber, Double secondNumber) {
6 | return firstNumber + secondNumber;
7 | }
8 |
9 | public Double subtraction(Double firstNumber, Double secondNumber) {
10 | return firstNumber - secondNumber;
11 | }
12 |
13 | public Double multiplication(Double firstNumber, Double secondNumber) {
14 | return firstNumber * secondNumber;
15 | }
16 |
17 | public Double division(Double firstNumber, Double secondNumber) {
18 | if (secondNumber.equals(0D))
19 | throw new ArithmeticException("Impossible to divide by zero!");
20 | return firstNumber / secondNumber;
21 | }
22 |
23 | public Double mean(Double firstNumber, Double secondNumber) {
24 | return (firstNumber + secondNumber) / 2;
25 | }
26 |
27 | public Double squareRoot(Double number) {
28 | return (Double) Math.sqrt(number);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/S03_FirstStepsInJUnit5WithJava/src/test/java/br/com/erudio/ArraysCompareTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import java.util.Arrays;
6 | import java.util.concurrent.TimeUnit;
7 |
8 | import org.junit.jupiter.api.Test;
9 | import org.junit.jupiter.api.Timeout;
10 |
11 | class ArraysCompareTest {
12 |
13 | @Test
14 | void test() {
15 | int[] numbers = {25,8,21,32,3};
16 | int[] expectedArray = {3,8,21,25,32};
17 |
18 | Arrays.sort(numbers);
19 |
20 | assertArrayEquals(numbers, expectedArray);
21 | }
22 |
23 | @Test
24 | // @Timeout(1)
25 | @Timeout(value = 15, unit = TimeUnit.MILLISECONDS)
26 | void testSortPerformance() {
27 |
28 | int[] numbers = {25,8,21,32,3};
29 | for (int i = 0; i < 10000000; i++) {
30 | numbers[0] = i;
31 | Arrays.sort(numbers);
32 | }
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/S03_FirstStepsInJUnit5WithJava/src/test/java/br/com/erudio/FooBarTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | // import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class FooBarTest {
8 |
9 | @Test
10 | void test() {
11 | // fail("Not yet implemented");
12 | System.out.println("Hello JUnit 5!");
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | br.com.erudio
4 | automated-tests-with-java-erudio
5 | 0.0.1-SNAPSHOT
6 |
7 | 19
8 | 5.9.2
9 | 19
10 | 19
11 | 3.10.1
12 |
13 |
14 |
15 |
16 | org.junit.jupiter
17 | junit-jupiter
18 | ${junit.version}
19 | test
20 |
21 |
22 |
23 |
24 |
25 |
26 | org.apache.maven.plugins
27 | maven-compiler-plugin
28 |
29 | ${java.version}
30 | ${java.version}
31 |
32 | ${maven.compiler.plugin.version}
33 |
34 |
35 | org.apache.maven.plugins
36 | maven-surefire-plugin
37 | 3.0.0-M9
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/src/main/java/br/com/erudio/math/SimpleMath.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.math;
2 |
3 | public class SimpleMath {
4 |
5 | public Double sum(Double firstNumber, Double secondNumber) {
6 | return firstNumber + secondNumber;
7 | }
8 |
9 | public Double subtraction(Double firstNumber, Double secondNumber) {
10 | return firstNumber - secondNumber;
11 | }
12 |
13 | public Double multiplication(Double firstNumber, Double secondNumber) {
14 | return firstNumber * secondNumber;
15 | }
16 |
17 | public Double division(Double firstNumber, Double secondNumber) {
18 | if (secondNumber.equals(0D))
19 | throw new ArithmeticException("Impossible to divide by zero!");
20 | return firstNumber / secondNumber;
21 | }
22 |
23 | public Double mean(Double firstNumber, Double secondNumber) {
24 | return (firstNumber + secondNumber) / 2;
25 | }
26 |
27 | public Double squareRoot(Double number) {
28 | return (Double) Math.sqrt(number);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/src/test/java/br/com/erudio/ArraysCompareTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import java.util.Arrays;
6 | import java.util.concurrent.TimeUnit;
7 |
8 | import org.junit.jupiter.api.Test;
9 | import org.junit.jupiter.api.Timeout;
10 |
11 | class ArraysCompareTest {
12 |
13 | @Test
14 | void test() {
15 | int[] numbers = {25,8,21,32,3};
16 | int[] expectedArray = {3,8,21,25,32};
17 |
18 | Arrays.sort(numbers);
19 |
20 | assertArrayEquals(numbers, expectedArray);
21 | }
22 |
23 | @Test
24 | // @Timeout(1)
25 | @Timeout(value = 15, unit = TimeUnit.MILLISECONDS)
26 | void testSortPerformance() {
27 |
28 | int[] numbers = {25,8,21,32,3};
29 | for (int i = 0; i < 10000000; i++) {
30 | numbers[0] = i;
31 | Arrays.sort(numbers);
32 | }
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/src/test/java/br/com/erudio/FooBarTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | // import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class FooBarTest {
8 |
9 | @Test
10 | void test() {
11 | // fail("Not yet implemented");
12 | System.out.println("Hello JUnit 5!");
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/src/test/java/br/com/erudio/MethodOrderedByNameTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.junit.jupiter.api.MethodOrderer;
4 | import org.junit.jupiter.api.Order;
5 | import org.junit.jupiter.api.Test;
6 | import org.junit.jupiter.api.TestMethodOrder;
7 |
8 | @Order(2)
9 | @TestMethodOrder(MethodOrderer.MethodName.class)
10 | class MethodOrderedByNameTest {
11 |
12 | @Test
13 | void testC() {
14 | System.out.println("Running Test C");
15 | }
16 |
17 | @Test
18 | void testD() {
19 | System.out.println("Running Test D");
20 | }
21 |
22 | @Test
23 | void testA() {
24 | System.out.println("Running Test A");
25 | }
26 |
27 | @Test
28 | void testB() {
29 | System.out.println("Running Test B");
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/src/test/java/br/com/erudio/MethodOrderedByOrderIndexTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.MethodOrderer;
5 | import org.junit.jupiter.api.Order;
6 | import org.junit.jupiter.api.Test;
7 | import org.junit.jupiter.api.TestInstance;
8 | import org.junit.jupiter.api.TestMethodOrder;
9 |
10 | //@Order(3)
11 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
12 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
13 | class MethodOrderedByOrderIndexTest {
14 |
15 | StringBuilder actualValue = new StringBuilder("");
16 |
17 | @AfterEach
18 | void afterEach() {
19 | System.out.println("The actual value is: " + actualValue);
20 | }
21 |
22 | @Test
23 | @Order(1)
24 | void testC() {
25 | System.out.println("Running Test C");
26 | actualValue.append("1");
27 | }
28 |
29 | @Test
30 | @Order(2)
31 | void testD() {
32 | System.out.println("Running Test D");
33 | actualValue.append("2");
34 | }
35 |
36 | @Test
37 | @Order(3)
38 | void testA() {
39 | System.out.println("Running Test A");
40 | actualValue.append("3");
41 | }
42 |
43 | @Test
44 | @Order(4)
45 | void testB() {
46 | System.out.println("Running Test B");
47 | actualValue.append("4");
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/src/test/java/br/com/erudio/MethodOrderedRandonlyTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.junit.jupiter.api.MethodOrderer;
4 | import org.junit.jupiter.api.Order;
5 | import org.junit.jupiter.api.Test;
6 | import org.junit.jupiter.api.TestMethodOrder;
7 |
8 | @Order(1)
9 | @TestMethodOrder(MethodOrderer.Random.class)
10 | class MethodOrderedRandonlyTest {
11 |
12 | @Test
13 | void testA() {
14 | System.out.println("Running Test A");
15 | }
16 |
17 | @Test
18 | void testB() {
19 | System.out.println("Running Test B");
20 | }
21 |
22 | @Test
23 | void testC() {
24 | System.out.println("Running Test C");
25 | }
26 |
27 | @Test
28 | void testD() {
29 | System.out.println("Running Test D");
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/src/test/java/br/com/erudio/math/DemoRepeatedTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.math;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.DisplayName;
7 | import org.junit.jupiter.api.RepeatedTest;
8 | import org.junit.jupiter.api.RepetitionInfo;
9 | import org.junit.jupiter.api.TestInfo;
10 |
11 | class DemoRepeatedTest {
12 |
13 | SimpleMath math;
14 |
15 | @BeforeEach
16 | void beforeEachMethod() {
17 | math = new SimpleMath();
18 | System.out.println("Running @BeforeEach method!");
19 | }
20 |
21 | @RepeatedTest(value = 3, name = "{displayName}. Repetition "
22 | + "{currentRepetition} of {totalRepetitions}!")
23 | @DisplayName("Test Division by Zero")
24 | void testDivision_When_FirstNumberIsDividedByZero_ShouldThrowArithmeticException(
25 | RepetitionInfo repetitionInfo,
26 | TestInfo testInfo
27 | ) {
28 |
29 | System.out.println("Repetition N° " + repetitionInfo.getCurrentRepetition() +
30 | " of " + repetitionInfo.getTotalRepetitions());
31 | System.out.println("Running " + testInfo.getTestMethod().get().getName());
32 |
33 | //given
34 | double firstNumber = 6.2D;
35 | double secondNumber = 0D;
36 |
37 | var expectedMessage = "Impossible to divide by zero!";
38 |
39 | //when & then
40 | ArithmeticException actual = assertThrows(
41 | ArithmeticException.class, () -> {
42 | //when & then
43 | math.division(firstNumber, secondNumber);
44 | }, () -> "Division by zero should throw an ArithmeticException");
45 |
46 | assertEquals(expectedMessage, actual.getMessage(),
47 | () -> "Unexpected exception message!");
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/src/test/java/br/com/erudio/math/SimpleMathTestS4.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.math;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertNotNull;
5 |
6 | import java.util.stream.Stream;
7 |
8 | import org.junit.jupiter.api.BeforeEach;
9 | import org.junit.jupiter.api.DisplayName;
10 | import org.junit.jupiter.params.ParameterizedTest;
11 | import org.junit.jupiter.params.provider.Arguments;
12 | import org.junit.jupiter.params.provider.CsvFileSource;
13 | import org.junit.jupiter.params.provider.CsvSource;
14 | import org.junit.jupiter.params.provider.MethodSource;
15 | import org.junit.jupiter.params.provider.ValueSource;
16 |
17 | @DisplayName("Test Math Operations in SimpleMath Class")
18 | class SimpleMathTestS4 {
19 |
20 | SimpleMath math;
21 |
22 | @BeforeEach
23 | void beforeEachMethod() {
24 | math = new SimpleMath();
25 | }
26 |
27 | @ParameterizedTest
28 | @ValueSource(strings = {"Pelé", "Senna", "Keith Moon"})
29 | void testValueSource(String firsName) {
30 | System.out.println(firsName);
31 | assertNotNull(firsName);
32 | }
33 |
34 | @DisplayName("Test double sbtraction [firstNumber, secondNumber, expected]")
35 | @ParameterizedTest
36 | //@MethodSource("testDivisionInputParameters")
37 | //@MethodSource()
38 | /**
39 | @CsvSource({
40 | "6.2, 2, 3.1",
41 | "71, 14, 5.07",
42 | "18.3, 3.1, 5.90"
43 | })
44 | @CsvSource({
45 | "Pelé, Football",
46 | "Senna, F1",
47 | "Keith Moon, ''"
48 | })
49 | */
50 | @CsvFileSource(resources = "/testDivision.csv")
51 | void testDivision(double firstNumber, double secondNumber, double expected) {
52 |
53 | System.out.println("Test " + firstNumber + " / " +
54 | secondNumber + " = " + expected + "!");
55 |
56 | Double actual = math.division(firstNumber, secondNumber);
57 |
58 | assertEquals(expected, actual, 2D,
59 | () -> firstNumber + "/" + secondNumber +
60 | " did not produce " + expected + "!");
61 | }
62 |
63 | //public static Stream testDivisionInputParameters() {
64 | /**
65 | public static Stream testDivision() {
66 | return Stream.of(
67 | Arguments.of(6.2D, 2D, 3.1D),
68 | Arguments.of(71D, 14D, 5.07D),
69 | Arguments.of(18.3, 3.1D, 5.90D)
70 | );
71 | }
72 | */
73 | }
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/src/test/resources/junit-platform.properties:
--------------------------------------------------------------------------------
1 | # junit.jupiter.testclass.order.default=org.junit.jupiter.api.ClassOrderer$OrderAnnotation
2 | # junit.jupiter.testmethod.order.default=org.junit.jupiter.api.MethodOrderer$OrderAnnotation
--------------------------------------------------------------------------------
/S04_AdvancedConceptsofJUnit5/src/test/resources/testDivision.csv:
--------------------------------------------------------------------------------
1 | 6.2,2,3.1
2 | 71,14,5.07
3 | 18.3,3.1,5.90
--------------------------------------------------------------------------------
/S05_JUnit5andTDD/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | br.com.erudio
4 | automated-tests-with-java-erudio
5 | 0.0.1-SNAPSHOT
6 |
7 | 19
8 | 5.9.2
9 | 19
10 | 19
11 | 3.10.1
12 |
13 |
14 |
15 |
16 | org.junit.jupiter
17 | junit-jupiter
18 | ${junit.version}
19 | test
20 |
21 |
22 |
23 |
24 |
25 |
26 | org.apache.maven.plugins
27 | maven-compiler-plugin
28 |
29 | ${java.version}
30 | ${java.version}
31 |
32 | ${maven.compiler.plugin.version}
33 |
34 |
35 | org.apache.maven.plugins
36 | maven-surefire-plugin
37 | 3.0.0-M9
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/S05_JUnit5andTDD/src/main/java/br/com/erudio/model/Person.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.model;
2 |
3 | import java.io.Serializable;
4 |
5 | public class Person implements Serializable{
6 |
7 | private static final long serialVersionUID = 1L;
8 |
9 | private Long id;
10 | private String firstName;
11 | private String lastName;
12 | private String address;
13 | private String gender;
14 | private String email;
15 |
16 | public Person() {}
17 |
18 | public Person(String firstName, String lastName, String address, String gender, String email) {
19 | this.firstName = firstName;
20 | this.lastName = lastName;
21 | this.address = address;
22 | this.gender = gender;
23 | this.email = email;
24 | }
25 |
26 | public Person(Long id, String firstName, String lastName, String address, String gender, String email) {
27 | this.id = id;
28 | this.firstName = firstName;
29 | this.lastName = lastName;
30 | this.address = address;
31 | this.gender = gender;
32 | this.email = email;
33 | }
34 |
35 | public Long getId() {
36 | return id;
37 | }
38 |
39 | public void setId(Long id) {
40 | this.id = id;
41 | }
42 |
43 | public String getFirstName() {
44 | return firstName;
45 | }
46 |
47 | public void setFirstName(String firstName) {
48 | this.firstName = firstName;
49 | }
50 |
51 | public String getLastName() {
52 | return lastName;
53 | }
54 |
55 | public void setLastName(String lastName) {
56 | this.lastName = lastName;
57 | }
58 |
59 | public String getAddress() {
60 | return address;
61 | }
62 |
63 | public void setAddress(String address) {
64 | this.address = address;
65 | }
66 |
67 | public String getGender() {
68 | return gender;
69 | }
70 |
71 | public void setGender(String gender) {
72 | this.gender = gender;
73 | }
74 |
75 | public String getEmail() {
76 | return email;
77 | }
78 |
79 | public void setEmail(String email) {
80 | this.email = email;
81 | }
82 |
83 | @Override
84 | public int hashCode() {
85 | final int prime = 31;
86 | int result = 1;
87 | result = prime * result + ((address == null) ? 0 : address.hashCode());
88 | result = prime * result + ((email == null) ? 0 : email.hashCode());
89 | result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
90 | result = prime * result + ((gender == null) ? 0 : gender.hashCode());
91 | result = prime * result + ((id == null) ? 0 : id.hashCode());
92 | result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
93 | return result;
94 | }
95 |
96 | @Override
97 | public boolean equals(Object obj) {
98 | if (this == obj)
99 | return true;
100 | if (obj == null)
101 | return false;
102 | if (getClass() != obj.getClass())
103 | return false;
104 | Person other = (Person) obj;
105 | if (address == null) {
106 | if (other.address != null)
107 | return false;
108 | } else if (!address.equals(other.address))
109 | return false;
110 | if (email == null) {
111 | if (other.email != null)
112 | return false;
113 | } else if (!email.equals(other.email))
114 | return false;
115 | if (firstName == null) {
116 | if (other.firstName != null)
117 | return false;
118 | } else if (!firstName.equals(other.firstName))
119 | return false;
120 | if (gender == null) {
121 | if (other.gender != null)
122 | return false;
123 | } else if (!gender.equals(other.gender))
124 | return false;
125 | if (id == null) {
126 | if (other.id != null)
127 | return false;
128 | } else if (!id.equals(other.id))
129 | return false;
130 | if (lastName == null) {
131 | if (other.lastName != null)
132 | return false;
133 | } else if (!lastName.equals(other.lastName))
134 | return false;
135 | return true;
136 | }
137 | }
--------------------------------------------------------------------------------
/S05_JUnit5andTDD/src/main/java/br/com/erudio/service/IPersonService.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.service;
2 |
3 | import br.com.erudio.model.Person;
4 |
5 | public interface IPersonService {
6 |
7 | Person createPerson(Person person);
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/S05_JUnit5andTDD/src/main/java/br/com/erudio/service/PersonService.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.service;
2 |
3 | import java.util.concurrent.atomic.AtomicLong;
4 |
5 | import br.com.erudio.model.Person;
6 |
7 | public class PersonService implements IPersonService {
8 |
9 | @Override
10 | public Person createPerson(Person person) {
11 |
12 | if (person.getEmail() == null || person.getEmail().isBlank())
13 | throw new IllegalArgumentException("The Person e-Mail is null or empty!");
14 |
15 | var id = new AtomicLong().incrementAndGet();
16 | person.setId(id);
17 | return person;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/S05_JUnit5andTDD/src/test/java/br/com/erudio/PersonServiceTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.DisplayName;
7 | import org.junit.jupiter.api.Test;
8 |
9 | import br.com.erudio.model.Person;
10 | import br.com.erudio.service.IPersonService;
11 | import br.com.erudio.service.PersonService;
12 |
13 | public class PersonServiceTest {
14 |
15 | IPersonService service;
16 | Person person;
17 |
18 | @BeforeEach
19 | void setup() {
20 | service = new PersonService();
21 | person = new Person(
22 | "Keith",
23 | "Moon",
24 | "kmoon@erudio.com.br",
25 | "Wembley - UK",
26 | "Male"
27 | );
28 | }
29 |
30 | @DisplayName("When Create a Person with Success Should Return a Person Object")
31 | @Test
32 | void testCreatePerson_WhenSucess_ShouldReturnPersonObject() {
33 |
34 | // Given / Arrange
35 |
36 | // When / Act
37 | Person actual = service.createPerson(person);
38 |
39 | // Then / Assert
40 | assertNotNull(actual, () -> "The createPerson() should not have returned null!");
41 | }
42 |
43 | @DisplayName("When Create a Person with Success Should Contains Valid Fields in Returned Person Object")
44 | @Test
45 | void testCreatePerson_WhenSucess_ShouldContainsValidFieldsInReturnedPersonObject() {
46 |
47 | // Given / Arrange
48 |
49 | // When / Act
50 | Person actual = service.createPerson(person);
51 |
52 | // Then / Assert
53 | assertNotNull(person.getId(), () -> "Person ID is Missing");
54 | assertEquals(
55 | person.getFirstName(),
56 | actual.getFirstName(),
57 | () -> "The Person FistName is Incorrect!");
58 | assertEquals(
59 | person.getLastName(),
60 | actual.getLastName(),
61 | () -> "The Person LastName is Incorrect!");
62 | assertEquals(
63 | person.getAddress(),
64 | actual.getAddress(),
65 | () -> "The Person Address is Incorrect!");
66 | assertEquals(
67 | person.getGender(),
68 | actual.getGender(),
69 | () -> "The Person Gender is Incorrect!");
70 | assertEquals(
71 | person.getEmail(),
72 | actual.getEmail(),
73 | () -> "The Person Email is Incorrect!");
74 | }
75 |
76 | @DisplayName("When Create a Person with null e-Mail Should throw Exception")
77 | @Test
78 | void testCreatePerson_WhithNullEMail_ShouldThrowIllegalArgumentException() {
79 | // Given / Arrange
80 | person.setEmail(null);
81 |
82 | var expectedMessage = "The Person e-Mail is null or empty!";
83 |
84 | // When / Act & Then / Assert
85 | IllegalArgumentException exception = assertThrows(
86 | IllegalArgumentException.class,
87 | () -> service.createPerson(person),
88 | () -> "Empty e-Mail should have cause an IllegalArgumentException!"
89 | );
90 |
91 | // Then / Assert
92 | assertEquals(
93 | expectedMessage,
94 | exception.getMessage(),
95 | () -> "Exception error message is incorrect!");
96 | }
97 | }
--------------------------------------------------------------------------------
/S06_MockitosFirstSteps/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | br.com.erudio
4 | automated-tests-with-java-erudio
5 | 0.0.1-SNAPSHOT
6 |
7 | 19
8 | 5.9.2
9 | 5.2.0
10 | 2.2
11 | 19
12 | 19
13 | 3.10.1
14 |
15 |
16 |
17 |
18 | org.junit.jupiter
19 | junit-jupiter
20 | ${junit.version}
21 | test
22 |
23 |
24 |
25 | org.mockito
26 | mockito-junit-jupiter
27 | ${mockito.version}
28 | test
29 |
30 |
31 |
32 | org.hamcrest
33 | hamcrest
34 | ${hamcrest.version}
35 | test
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 | org.apache.maven.plugins
44 | maven-compiler-plugin
45 |
46 | ${java.version}
47 | ${java.version}
48 |
49 | ${maven.compiler.plugin.version}
50 |
51 |
52 | org.apache.maven.plugins
53 | maven-surefire-plugin
54 | 3.0.0-M9
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/S06_MockitosFirstSteps/src/main/java/br/com/erudio/business/CourseBusiness.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import br.com.erudio.service.CourseService;
7 |
8 | // CourseBusiness = SUT - System (Method) Under Test
9 | public class CourseBusiness {
10 |
11 | // CourseService is a Dependency
12 | private CourseService service;
13 |
14 | public CourseBusiness(CourseService service) {
15 | this.service = service;
16 | }
17 |
18 | public List retriveCoursesRelatedToSpring(String student) {
19 |
20 | var filteredCourses = new ArrayList();
21 | if("Foo Bar".equals(student)) return filteredCourses;
22 | var allCourses = service.retrieveCourses(student);
23 |
24 | for (String course : allCourses) {
25 | if (course.contains("Spring")) {
26 | filteredCourses.add(course);
27 | }
28 | }
29 |
30 | return filteredCourses;
31 | }
32 |
33 | public void deleteCoursesNotRelatedToSpring(String student) {
34 |
35 | var allCourses = service.retrieveCourses(student);
36 |
37 | for (String course : allCourses) {
38 | if (!course.contains("Spring")) {
39 | service.deleteCourse(course);
40 | }
41 | }
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/S06_MockitosFirstSteps/src/main/java/br/com/erudio/service/CourseService.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.service;
2 |
3 | import java.util.List;
4 |
5 | public interface CourseService {
6 |
7 | public List retrieveCourses(String student);
8 | public List doSomething(String student);
9 | public void deleteCourse(String course);
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/S06_MockitosFirstSteps/src/test/java/br/com/erudio/business/CourseBusinessMockTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.mockito.Mockito.*;
5 |
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | import br.com.erudio.service.CourseService;
13 |
14 | class CourseBusinessMockTest {
15 |
16 | CourseService mockService;
17 | CourseBusiness business;
18 | List courses;
19 |
20 | @BeforeEach
21 | void setup() {
22 |
23 | // Given / Arrange
24 | mockService = mock(CourseService.class);
25 | business = new CourseBusiness(mockService);
26 |
27 | courses = Arrays.asList(
28 | "REST API's RESTFul do 0 à Azure com ASP.NET Core 5 e Docker",
29 | "Agile Desmistificado com Scrum, XP, Kanban e Trello",
30 | "Spotify Engineering Culture Desmistificado",
31 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Java e Docker",
32 | "Docker do Zero à Maestria - Contêinerização Desmistificada",
33 | "Docker para Amazon AWS Implante Apps Java e .NET com Travis CI",
34 | "Microsserviços do 0 com Spring Cloud, Spring Boot e Docker",
35 | "Arquitetura de Microsserviços do 0 com ASP.NET, .NET 6 e C#",
36 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Kotlin e Docker",
37 | "Kotlin para DEV's Java: Aprenda a Linguagem Padrão do Android",
38 | "Microsserviços do 0 com Spring Cloud, Kotlin e Docker"
39 | );
40 | }
41 |
42 | @Test
43 | void testCoursesRelatedToSpring_When_UsingAMock() {
44 |
45 | // Given / Arrange
46 | when(mockService.retrieveCourses("Leandro"))
47 | .thenReturn(courses);
48 |
49 | // When / Act
50 | var filteredCourses =
51 | business.retriveCoursesRelatedToSpring("Leandro");
52 |
53 | // Then / Assert
54 | assertEquals(4, filteredCourses.size());
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/S06_MockitosFirstSteps/src/test/java/br/com/erudio/business/CourseBusinessStubTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | import br.com.erudio.service.CourseService;
8 | import br.com.erudio.service.stubs.CourseServiceStub;
9 |
10 | class CourseBusinessStubTest {
11 |
12 | @Test
13 | void testCoursesRelatedToSpring_When_UsingAStub() {
14 |
15 | // Given / Arrange
16 | CourseService stubService = new CourseServiceStub();
17 | CourseBusiness business = new CourseBusiness(stubService);
18 |
19 | // When / Act
20 | var filteredCourses =
21 | business.retriveCoursesRelatedToSpring("Leandro");
22 |
23 | // Then / Assert
24 | assertEquals(4, filteredCourses.size());
25 | }
26 |
27 | @Test
28 | void testCoursesRelatedToSpring_When_UsingAFooBarStudent() {
29 |
30 | // Given / Arrange
31 | CourseService stubService = new CourseServiceStub();
32 | CourseBusiness business = new CourseBusiness(stubService);
33 |
34 | // When / Act
35 | var filteredCourses =
36 | business.retriveCoursesRelatedToSpring("Foo Bar");
37 |
38 | // Then / Assert
39 | assertEquals(0, filteredCourses.size());
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/S06_MockitosFirstSteps/src/test/java/br/com/erudio/business/ListTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 | import static org.mockito.Mockito.*;
5 |
6 | import java.util.List;
7 |
8 | import org.junit.jupiter.api.Test;
9 |
10 | public class ListTest {
11 |
12 | @Test
13 | void testMockingList_When_SizeIsCalled_ShouldReturn10() {
14 |
15 | // Given / Arrange
16 | List> list = mock(List.class);
17 | when(list.size()).thenReturn(10);
18 |
19 | // When / Act & Then / Assert
20 | assertEquals(10, list.size());
21 | assertEquals(10, list.size());
22 | assertEquals(10, list.size());
23 | }
24 |
25 | @Test
26 | void testMockingList_When_SizeIsCalled_ShouldReturnMultipleValues() {
27 |
28 | // Given / Arrange
29 | List> list = mock(List.class);
30 | when(list.size()).thenReturn(10).thenReturn(20);
31 |
32 | // When / Act & Then / Assert
33 | assertEquals(10, list.size());
34 | assertEquals(20, list.size());
35 | assertEquals(20, list.size());
36 | }
37 |
38 | @Test
39 | void testMockingList_When_GetIsCalled_ShouldReturnErudio() {
40 |
41 | // Given / Arrange
42 | var list = mock(List.class);
43 | when(list.get(0)).thenReturn("Erudio");
44 |
45 | // When / Act & Then / Assert
46 | assertEquals("Erudio", list.get(0));
47 | assertNull(list.get(1));
48 | }
49 |
50 | @Test
51 | void testMockingList_When_GetIsCalledWithArgumentMatcher_ShouldReturnErudio() {
52 |
53 | // Given / Arrange
54 | var list = mock(List.class);
55 |
56 | // If you are using argument matchers, all arguments
57 | // have to be provided by matchers.
58 | when(list.get(anyInt())).thenReturn("Erudio");
59 |
60 | // When / Act & Then / Assert
61 | assertEquals("Erudio", list.get(anyInt()));
62 | assertEquals("Erudio", list.get(anyInt()));
63 | }
64 |
65 | @Test
66 | void testMockingList_When_ThrowsAnException() {
67 |
68 | // Given / Arrange
69 | var list = mock(List.class);
70 |
71 | // If you are using argument matchers, all arguments
72 | // have to be provided by matchers.
73 | when(list.get(anyInt())).thenThrow(new RuntimeException("Foo Bar!!"));
74 |
75 | // When / Act & Then / Assert
76 | assertThrows(RuntimeException.class,
77 | () -> {
78 | // When / Act
79 | list.get(anyInt());},
80 | () -> "Should have throw an RuntimeException");
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/S06_MockitosFirstSteps/src/test/java/br/com/erudio/business/ListWithBDDTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.mockito.Mockito.*;
4 | import static org.mockito.BDDMockito.*;
5 |
6 | import static org.hamcrest.MatcherAssert.assertThat;
7 | import static org.hamcrest.Matchers.*;
8 | import static org.junit.jupiter.api.Assertions.assertNull;
9 | import static org.junit.jupiter.api.Assertions.assertThrows;
10 |
11 | import java.util.List;
12 |
13 | import org.junit.jupiter.api.Test;
14 |
15 | public class ListWithBDDTest {
16 |
17 | @Test
18 | void testMockingList_When_SizeIsCalled_ShouldReturn10() {
19 |
20 | // Given / Arrange
21 | List> list = mock(List.class);
22 | given(list.size()).willReturn(10);
23 |
24 | // When / Act & Then / Assert
25 | assertThat(list.size(), is(10));
26 | assertThat(list.size(), is(10));
27 | assertThat(list.size(), is(10));
28 | }
29 |
30 | @Test
31 | void testMockingList_When_SizeIsCalled_ShouldReturnMultipleValues() {
32 |
33 | // Given / Arrange
34 | List> list = mock(List.class);
35 | given(list.size()).willReturn(10).willReturn(20);
36 |
37 | // When / Act & Then / Assert
38 | assertThat(list.size(), is(10));
39 | assertThat(list.size(), is(20));
40 | assertThat(list.size(), is(20));
41 | }
42 |
43 | @Test
44 | void testMockingList_When_GetIsCalled_ShouldReturnErudio() {
45 |
46 | // Given / Arrange
47 | var list = mock(List.class);
48 | given(list.get(0)).willReturn("Erudio");
49 |
50 | // When / Act & Then / Assert
51 | assertThat(list.get(0), is("Erudio"));
52 | assertNull(list.get(1));
53 | }
54 |
55 | @Test
56 | void testMockingList_When_GetIsCalledWithArgumentMatcher_ShouldReturnErudio() {
57 |
58 | // Given / Arrange
59 | var list = mock(List.class);
60 |
61 | // If you are using argument matchers, all arguments
62 | // have to be provided by matchers.
63 | given(list.get(anyInt())).willReturn("Erudio");
64 |
65 | // When / Act & Then / Assert
66 | assertThat(list.get(anyInt()), is("Erudio"));
67 | assertThat(list.get(anyInt()), is("Erudio"));
68 | }
69 |
70 | @Test
71 | void testMockingList_When_ThrowsAnException() {
72 |
73 | // Given / Arrange
74 | var list = mock(List.class);
75 |
76 | // If you are using argument matchers, all arguments
77 | // have to be provided by matchers.
78 | given(list.get(anyInt())).willThrow(new RuntimeException("Foo Bar!!"));
79 |
80 | // When / Act & Then / Assert
81 | assertThrows(RuntimeException.class,
82 | () -> {
83 | // When / Act
84 | list.get(anyInt());},
85 | () -> "Should have throw an RuntimeException");
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/S06_MockitosFirstSteps/src/test/java/br/com/erudio/service/stubs/CourseServiceStub.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.service.stubs;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | import br.com.erudio.service.CourseService;
7 |
8 | public class CourseServiceStub implements CourseService{
9 |
10 | public List retrieveCourses(String student) {
11 | return Arrays.asList(
12 | "REST API's RESTFul do 0 à Azure com ASP.NET Core 5 e Docker",
13 | "Agile Desmistificado com Scrum, XP, Kanban e Trello",
14 | "Spotify Engineering Culture Desmistificado",
15 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Java e Docker",
16 | "Docker do Zero à Maestria - Contêinerização Desmistificada",
17 | "Docker para Amazon AWS Implante Apps Java e .NET com Travis CI",
18 | "Microsserviços do 0 com Spring Cloud, Spring Boot e Docker",
19 | "Arquitetura de Microsserviços do 0 com ASP.NET, .NET 6 e C#",
20 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Kotlin e Docker",
21 | "Kotlin para DEV's Java: Aprenda a Linguagem Padrão do Android",
22 | "Microsserviços do 0 com Spring Cloud, Kotlin e Docker"
23 | );
24 | }
25 |
26 | @Override
27 | public List doSomething(String student) {
28 | // TODO Auto-generated method stub
29 | return null;
30 | }
31 |
32 | @Override
33 | public void deleteCourse(String course) {
34 | // TODO Auto-generated method stub
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | br.com.erudio
4 | automated-tests-with-java-erudio
5 | 0.0.1-SNAPSHOT
6 |
7 | 19
8 | 5.9.2
9 | 5.2.0
10 | 2.2
11 | 19
12 | 19
13 | 3.10.1
14 |
15 |
16 |
17 |
18 | org.junit.jupiter
19 | junit-jupiter
20 | ${junit.version}
21 | test
22 |
23 |
24 |
25 | org.mockito
26 | mockito-junit-jupiter
27 | ${mockito.version}
28 | test
29 |
30 |
31 |
32 | org.mockito
33 | mockito-inline
34 | ${mockito.version}
35 | test
36 |
37 |
38 |
39 | org.hamcrest
40 | hamcrest
41 | ${hamcrest.version}
42 | test
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | org.apache.maven.plugins
51 | maven-compiler-plugin
52 |
53 | ${java.version}
54 | ${java.version}
55 |
56 | ${maven.compiler.plugin.version}
57 |
58 |
59 | org.apache.maven.plugins
60 | maven-surefire-plugin
61 | 3.0.0-M9
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/main/java/br/com/erudio/business/CourseBusiness.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import br.com.erudio.service.CourseService;
7 |
8 | // CourseBusiness = SUT - System (Method) Under Test
9 | public class CourseBusiness {
10 |
11 | // CourseService is a Dependency
12 | private CourseService service;
13 |
14 | public CourseBusiness(CourseService service) {
15 | this.service = service;
16 | }
17 |
18 | public List retriveCoursesRelatedToSpring(String student) {
19 |
20 | var filteredCourses = new ArrayList();
21 | if("Foo Bar".equals(student)) return filteredCourses;
22 | var allCourses = service.retrieveCourses(student);
23 |
24 | for (String course : allCourses) {
25 | if (course.contains("Spring")) {
26 | filteredCourses.add(course);
27 | }
28 | }
29 |
30 | return filteredCourses;
31 | }
32 |
33 | public void deleteCoursesNotRelatedToSpring(String student) {
34 |
35 | var allCourses = service.retrieveCourses(student);
36 |
37 | for (String course : allCourses) {
38 | if (!course.contains("Spring")) {
39 | service.deleteCourse(course);
40 | }
41 | }
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/main/java/br/com/erudio/mockito/constructor/CheckoutService.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.constructor;
2 |
3 | import java.math.BigDecimal;
4 |
5 | public class CheckoutService {
6 |
7 | public BigDecimal purchaseProduct(String productName, String customerId) {
8 |
9 | // Any arbitrary implementation
10 | PaymentProcessor paymentProcessor = new PaymentProcessor();
11 | return paymentProcessor.chargeCustomer(customerId, BigDecimal.TEN);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/main/java/br/com/erudio/mockito/constructor/PaymentProcessor.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.constructor;
2 |
3 | import java.math.BigDecimal;
4 |
5 | public class PaymentProcessor {
6 |
7 | private boolean allowForeignCurrencies;
8 | private String fallbackOption;
9 | private BigDecimal taxRate;
10 |
11 | public PaymentProcessor() {
12 | this(false, "DEBIT", new BigDecimal("19.00"));
13 | }
14 |
15 | public PaymentProcessor(String fallbackOption, BigDecimal taxRate) {
16 | this(false, fallbackOption, taxRate);
17 | }
18 |
19 | public PaymentProcessor(boolean allowForeignCurrencies, String fallbackOption, BigDecimal taxRate) {
20 | this.allowForeignCurrencies = allowForeignCurrencies;
21 | this.fallbackOption = fallbackOption;
22 | this.taxRate = taxRate;
23 | }
24 |
25 | public BigDecimal chargeCustomer(String customerId, BigDecimal netPrice) {
26 |
27 | // Any arbitrary implementation
28 | System.out.println("About to charge customer: " + customerId);
29 | return BigDecimal.ZERO;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/main/java/br/com/erudio/mockito/services/Order.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.services;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | public class Order {
6 |
7 | private String id;
8 | private String productName;
9 | private Long amount;
10 | private LocalDateTime creationDate;
11 |
12 | public Order() {}
13 |
14 | public String getProductName() {
15 | return productName;
16 | }
17 |
18 | public void setProductName(String productName) {
19 | this.productName = productName;
20 | }
21 |
22 | public Long getAmount() {
23 | return amount;
24 | }
25 |
26 | public void setAmount(Long amount) {
27 | this.amount = amount;
28 | }
29 |
30 | public String getId() {
31 | return id;
32 | }
33 |
34 | public void setId(String id) {
35 | this.id = id;
36 | }
37 |
38 | public LocalDateTime getCreationDate() {
39 | return creationDate;
40 | }
41 |
42 | public void setCreationDate(LocalDateTime creationDate) {
43 | this.creationDate = creationDate;
44 | }
45 | }
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/main/java/br/com/erudio/mockito/services/OrderService.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.services;
2 |
3 | import java.time.LocalDateTime;
4 | import java.util.UUID;
5 |
6 | public class OrderService {
7 |
8 | public Order createOrder(String productName, Long amount, String orderID) {
9 |
10 | Order order = new Order();
11 |
12 | order.setId(orderID == null ? UUID.randomUUID().toString() : orderID);
13 | order.setCreationDate(LocalDateTime.now());
14 | order.setAmount(amount);
15 | order.setProductName(productName);
16 | return order;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/main/java/br/com/erudio/mockito/staticwithparams/MyUtils.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.staticwithparams;
2 |
3 | public class MyUtils {
4 |
5 | public static String getWelcomeMessage(String username, boolean isCustomer) {
6 |
7 | if (isCustomer) {
8 | return "Dear " + username;
9 | } else {
10 | return "Hello " + username;
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/main/java/br/com/erudio/service/CourseService.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.service;
2 |
3 | import java.util.List;
4 |
5 | public interface CourseService {
6 |
7 | public List retrieveCourses(String student);
8 | public List doSomething(String student);
9 | public void deleteCourse(String course);
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/business/CourseBusinessMockTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.mockito.Mockito.*;
5 |
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | import br.com.erudio.service.CourseService;
13 |
14 | class CourseBusinessMockTest {
15 |
16 | CourseService mockService;
17 | CourseBusiness business;
18 | List courses;
19 |
20 | @BeforeEach
21 | void setup() {
22 |
23 | // Given / Arrange
24 | mockService = mock(CourseService.class);
25 | business = new CourseBusiness(mockService);
26 |
27 | courses = Arrays.asList(
28 | "REST API's RESTFul do 0 à Azure com ASP.NET Core 5 e Docker",
29 | "Agile Desmistificado com Scrum, XP, Kanban e Trello",
30 | "Spotify Engineering Culture Desmistificado",
31 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Java e Docker",
32 | "Docker do Zero à Maestria - Contêinerização Desmistificada",
33 | "Docker para Amazon AWS Implante Apps Java e .NET com Travis CI",
34 | "Microsserviços do 0 com Spring Cloud, Spring Boot e Docker",
35 | "Arquitetura de Microsserviços do 0 com ASP.NET, .NET 6 e C#",
36 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Kotlin e Docker",
37 | "Kotlin para DEV's Java: Aprenda a Linguagem Padrão do Android",
38 | "Microsserviços do 0 com Spring Cloud, Kotlin e Docker"
39 | );
40 | }
41 |
42 | @Test
43 | void testCoursesRelatedToSpring_When_UsingAMock() {
44 |
45 | // Given / Arrange
46 | when(mockService.retrieveCourses("Leandro"))
47 | .thenReturn(courses);
48 |
49 | // When / Act
50 | var filteredCourses =
51 | business.retriveCoursesRelatedToSpring("Leandro");
52 |
53 | // Then / Assert
54 | assertEquals(4, filteredCourses.size());
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/business/CourseBusinessStubTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | import br.com.erudio.service.CourseService;
8 | import br.com.erudio.service.stubs.CourseServiceStub;
9 |
10 | class CourseBusinessStubTest {
11 |
12 | @Test
13 | void testCoursesRelatedToSpring_When_UsingAStub() {
14 |
15 | // Given / Arrange
16 | CourseService stubService = new CourseServiceStub();
17 | CourseBusiness business = new CourseBusiness(stubService);
18 |
19 | // When / Act
20 | var filteredCourses =
21 | business.retriveCoursesRelatedToSpring("Leandro");
22 |
23 | // Then / Assert
24 | assertEquals(4, filteredCourses.size());
25 | }
26 |
27 | @Test
28 | void testCoursesRelatedToSpring_When_UsingAFooBarStudent() {
29 |
30 | // Given / Arrange
31 | CourseService stubService = new CourseServiceStub();
32 | CourseBusiness business = new CourseBusiness(stubService);
33 |
34 | // When / Act
35 | var filteredCourses =
36 | business.retriveCoursesRelatedToSpring("Foo Bar");
37 |
38 | // Then / Assert
39 | assertEquals(0, filteredCourses.size());
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/business/ListTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 | import static org.mockito.Mockito.*;
5 |
6 | import java.util.List;
7 |
8 | import org.junit.jupiter.api.Test;
9 |
10 | public class ListTest {
11 |
12 | @Test
13 | void testMockingList_When_SizeIsCalled_ShouldReturn10() {
14 |
15 | // Given / Arrange
16 | List> list = mock(List.class);
17 | when(list.size()).thenReturn(10);
18 |
19 | // When / Act & Then / Assert
20 | assertEquals(10, list.size());
21 | assertEquals(10, list.size());
22 | assertEquals(10, list.size());
23 | }
24 |
25 | @Test
26 | void testMockingList_When_SizeIsCalled_ShouldReturnMultipleValues() {
27 |
28 | // Given / Arrange
29 | List> list = mock(List.class);
30 | when(list.size()).thenReturn(10).thenReturn(20);
31 |
32 | // When / Act & Then / Assert
33 | assertEquals(10, list.size());
34 | assertEquals(20, list.size());
35 | assertEquals(20, list.size());
36 | }
37 |
38 | @Test
39 | void testMockingList_When_GetIsCalled_ShouldReturnErudio() {
40 |
41 | // Given / Arrange
42 | var list = mock(List.class);
43 | when(list.get(0)).thenReturn("Erudio");
44 |
45 | // When / Act & Then / Assert
46 | assertEquals("Erudio", list.get(0));
47 | assertNull(list.get(1));
48 | }
49 |
50 | @Test
51 | void testMockingList_When_GetIsCalledWithArgumentMatcher_ShouldReturnErudio() {
52 |
53 | // Given / Arrange
54 | var list = mock(List.class);
55 |
56 | // If you are using argument matchers, all arguments
57 | // have to be provided by matchers.
58 | when(list.get(anyInt())).thenReturn("Erudio");
59 |
60 | // When / Act & Then / Assert
61 | assertEquals("Erudio", list.get(anyInt()));
62 | assertEquals("Erudio", list.get(anyInt()));
63 | }
64 |
65 | @Test
66 | void testMockingList_When_ThrowsAnException() {
67 |
68 | // Given / Arrange
69 | var list = mock(List.class);
70 |
71 | // If you are using argument matchers, all arguments
72 | // have to be provided by matchers.
73 | when(list.get(anyInt())).thenThrow(new RuntimeException("Foo Bar!!"));
74 |
75 | // When / Act & Then / Assert
76 | assertThrows(RuntimeException.class,
77 | () -> {
78 | // When / Act
79 | list.get(anyInt());},
80 | () -> "Should have throw an RuntimeException");
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/business/ListWithBDDTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.mockito.Mockito.*;
4 | import static org.mockito.BDDMockito.*;
5 |
6 | import static org.hamcrest.MatcherAssert.assertThat;
7 | import static org.hamcrest.Matchers.*;
8 | import static org.junit.jupiter.api.Assertions.assertNull;
9 | import static org.junit.jupiter.api.Assertions.assertThrows;
10 |
11 | import java.util.List;
12 |
13 | import org.junit.jupiter.api.Test;
14 |
15 | public class ListWithBDDTest {
16 |
17 | @Test
18 | void testMockingList_When_SizeIsCalled_ShouldReturn10() {
19 |
20 | // Given / Arrange
21 | List> list = mock(List.class);
22 | given(list.size()).willReturn(10);
23 |
24 | // When / Act & Then / Assert
25 | assertThat(list.size(), is(10));
26 | assertThat(list.size(), is(10));
27 | assertThat(list.size(), is(10));
28 | }
29 |
30 | @Test
31 | void testMockingList_When_SizeIsCalled_ShouldReturnMultipleValues() {
32 |
33 | // Given / Arrange
34 | List> list = mock(List.class);
35 | given(list.size()).willReturn(10).willReturn(20);
36 |
37 | // When / Act & Then / Assert
38 | assertThat(list.size(), is(10));
39 | assertThat(list.size(), is(20));
40 | assertThat(list.size(), is(20));
41 | }
42 |
43 | @Test
44 | void testMockingList_When_GetIsCalled_ShouldReturnErudio() {
45 |
46 | // Given / Arrange
47 | var list = mock(List.class);
48 | given(list.get(0)).willReturn("Erudio");
49 |
50 | // When / Act & Then / Assert
51 | assertThat(list.get(0), is("Erudio"));
52 | assertNull(list.get(1));
53 | }
54 |
55 | @Test
56 | void testMockingList_When_GetIsCalledWithArgumentMatcher_ShouldReturnErudio() {
57 |
58 | // Given / Arrange
59 | var list = mock(List.class);
60 |
61 | // If you are using argument matchers, all arguments
62 | // have to be provided by matchers.
63 | given(list.get(anyInt())).willReturn("Erudio");
64 |
65 | // When / Act & Then / Assert
66 | assertThat(list.get(anyInt()), is("Erudio"));
67 | assertThat(list.get(anyInt()), is("Erudio"));
68 | }
69 |
70 | @Test
71 | void testMockingList_When_ThrowsAnException() {
72 |
73 | // Given / Arrange
74 | var list = mock(List.class);
75 |
76 | // If you are using argument matchers, all arguments
77 | // have to be provided by matchers.
78 | given(list.get(anyInt())).willThrow(new RuntimeException("Foo Bar!!"));
79 |
80 | // When / Act & Then / Assert
81 | assertThrows(RuntimeException.class,
82 | () -> {
83 | // When / Act
84 | list.get(anyInt());},
85 | () -> "Should have throw an RuntimeException");
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/mockito/HamcrestMatchersTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | import static org.hamcrest.MatcherAssert.*;
7 | import static org.hamcrest.Matchers.*;
8 |
9 | import org.junit.jupiter.api.Test;
10 |
11 | class HamcrestMatchersTest {
12 |
13 | @Test
14 | void testHamcrestMatchers() {
15 | // Given
16 | List scores = Arrays.asList(99, 100, 101, 105);
17 |
18 | //When & Then
19 | assertThat(scores, hasSize(4));
20 | assertThat(scores, hasItems(100, 101));
21 | assertThat(scores, everyItem(greaterThan(98)));
22 | assertThat(scores, everyItem(lessThan(106)));
23 |
24 | // Check Strings
25 | assertThat("", is(emptyString()));
26 | assertThat(null, is(emptyOrNullString()));
27 |
28 | // Arrays
29 | Integer[] myArray = {1, 2, 3};
30 | assertThat(myArray, arrayWithSize(3));
31 | assertThat(myArray, arrayContaining(1, 2, 3));
32 | assertThat(myArray, arrayContainingInAnyOrder(3, 2, 1));
33 |
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/mockito/SpyTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.mockito.ArgumentMatchers.anyString;
5 | import static org.mockito.Mockito.mock;
6 | import static org.mockito.Mockito.never;
7 | import static org.mockito.Mockito.spy;
8 | import static org.mockito.Mockito.verify;
9 | import static org.mockito.Mockito.when;
10 |
11 | import java.util.ArrayList;
12 | import java.util.List;
13 |
14 | import org.junit.jupiter.api.Test;
15 |
16 | public class SpyTest {
17 |
18 | @Test
19 | void testV1() {
20 | // Given / Arrange
21 | List mockArrayList = spy(ArrayList.class);
22 |
23 | // When / Act & Then / Assert
24 | assertEquals(0, mockArrayList.size());
25 |
26 | when(mockArrayList.size()).thenReturn(5);
27 | mockArrayList.add("Foo-Bar");
28 |
29 | assertEquals(5, mockArrayList.size());
30 | }
31 |
32 | @Test
33 | void testV2() {
34 | // Given / Arrange
35 | List spyArrayList = spy(ArrayList.class);
36 |
37 | // When / Act & Then / Assert
38 | assertEquals(0, spyArrayList.size());
39 |
40 | spyArrayList.add("Foo-Bar");
41 | assertEquals(1, spyArrayList.size());
42 |
43 | spyArrayList.remove("Foo-Bar");
44 | assertEquals(0, spyArrayList.size());
45 | }
46 |
47 | @Test
48 | void testV3() {
49 | List spyArrayList = spy(ArrayList.class);
50 | assertEquals(0, spyArrayList.size());
51 | when(spyArrayList.size()).thenReturn(5);
52 | assertEquals(5, spyArrayList.size());
53 | }
54 |
55 | @Test
56 | void testV4() {
57 | List spyArrayList = spy(ArrayList.class);
58 | spyArrayList.add("Foo-Bar");
59 |
60 | verify(spyArrayList).add("Foo-Bar");
61 | // verify(spyArrayList, never()).remove("Foo-Bar");
62 | verify(spyArrayList, never()).remove(anyString());
63 | verify(spyArrayList, never()).clear();
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/mockito/constructor/CheckoutServiceTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.constructor;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.mockito.ArgumentMatchers.any;
5 | import static org.mockito.ArgumentMatchers.anyString;
6 | import static org.mockito.Mockito.mockConstruction;
7 | import static org.mockito.Mockito.when;
8 |
9 | import java.math.BigDecimal;
10 |
11 | import org.junit.jupiter.api.Test;
12 | import org.mockito.MockedConstruction;
13 |
14 | class CheckoutServiceTest {
15 |
16 | @Test
17 | void testMockObjectConstruction() {
18 |
19 | //Given
20 | try(MockedConstruction mocked =
21 | mockConstruction(PaymentProcessor.class,
22 | (mock, context) ->
23 | {
24 | when(mock.chargeCustomer(
25 | anyString(),
26 | any(BigDecimal.class))).thenReturn(BigDecimal.TEN);
27 | }))
28 | {
29 |
30 | CheckoutService service = new CheckoutService();
31 |
32 | //When
33 | BigDecimal result = service.purchaseProduct("MacBook Pro", "42");
34 |
35 | //Then
36 | assertEquals(BigDecimal.TEN, result);
37 | assertEquals(1, mocked.constructed().size());
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/mockito/constructor/PaymentProcessorTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.constructor;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.mockito.MockedConstruction;
5 | import org.mockito.Mockito;
6 |
7 | import java.math.BigDecimal;
8 |
9 | import static org.junit.jupiter.api.Assertions.assertEquals;
10 | import static org.mockito.ArgumentMatchers.anyString;
11 | import static org.mockito.Mockito.*;
12 |
13 | class PaymentProcessorTest {
14 |
15 | @Test
16 | void mockObjectConstruction() {
17 |
18 | // A real object of the PaymentProcessor is returned
19 | System.out.println(new PaymentProcessor().chargeCustomer("42", BigDecimal.valueOf(42)));
20 |
21 | try (MockedConstruction mocked = mockConstruction(PaymentProcessor.class)) {
22 |
23 | // Every object creation is returning a mock from now on
24 | PaymentProcessor paymentProcessor = new PaymentProcessor();
25 |
26 | when(paymentProcessor.chargeCustomer(anyString(), any(BigDecimal.class))).thenReturn(BigDecimal.TEN);
27 |
28 | assertEquals(BigDecimal.TEN, paymentProcessor.chargeCustomer("42", BigDecimal.valueOf(42)));
29 | }
30 |
31 | // A real object of the PaymentProcessor is returned
32 | System.out.println(new PaymentProcessor().chargeCustomer("42", BigDecimal.valueOf(42)));
33 | }
34 |
35 | @Test
36 | void mockDifferentObjectConstruction() {
37 | try (MockedConstruction mocked = Mockito.mockConstruction(PaymentProcessor.class)) {
38 |
39 | PaymentProcessor firstInstance = new PaymentProcessor("PayPal", BigDecimal.TEN);
40 | PaymentProcessor secondInstance = new PaymentProcessor(true, "PayPal", BigDecimal.TEN);
41 |
42 | when(firstInstance.chargeCustomer(anyString(), any(BigDecimal.class))).thenReturn(BigDecimal.TEN);
43 | when(secondInstance.chargeCustomer(anyString(), any(BigDecimal.class))).thenReturn(BigDecimal.TEN);
44 |
45 | assertEquals(BigDecimal.TEN, firstInstance.chargeCustomer("42", BigDecimal.valueOf(42)));
46 | assertEquals(BigDecimal.TEN, secondInstance.chargeCustomer("42", BigDecimal.valueOf(42)));
47 | assertEquals(2, mocked.constructed().size());
48 | }
49 | }
50 |
51 | @Test
52 | void mockDifferentObjectConstructionWithAnswer() {
53 | try (MockedConstruction mocked = Mockito.mockConstructionWithAnswer(PaymentProcessor.class,
54 | // Default answer for the first mock
55 | invocation -> new BigDecimal("500.00"),
56 | // Additional answer for all further mocks
57 | invocation -> new BigDecimal("42.00"))) {
58 |
59 | PaymentProcessor firstInstance = new PaymentProcessor();
60 | PaymentProcessor secondInstance = new PaymentProcessor();
61 | PaymentProcessor thirdInstance = new PaymentProcessor();
62 |
63 | assertEquals(new BigDecimal("500.00"), firstInstance.chargeCustomer("42", BigDecimal.ZERO));
64 | assertEquals(new BigDecimal("42.00"), secondInstance.chargeCustomer("42", BigDecimal.ZERO));
65 | assertEquals(new BigDecimal("42.00"), thirdInstance.chargeCustomer("42", BigDecimal.ZERO));
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/mockito/services/OrderServiceTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.services;
2 |
3 | import java.time.LocalDateTime;
4 | import java.util.UUID;
5 |
6 | import static org.junit.jupiter.api.Assertions.assertEquals;
7 | import static org.mockito.Mockito.*;
8 |
9 | import org.junit.jupiter.api.DisplayName;
10 | import org.junit.jupiter.api.Test;
11 | import org.mockito.MockedStatic;
12 |
13 | class OrderServiceTest {
14 |
15 | private final OrderService service = new OrderService();
16 | private final UUID defaultUuid = UUID.fromString("8d8b30e3-de52-4f1c-a71c-9905a8043dac");
17 | private final LocalDateTime defaultLocalDateTime = LocalDateTime.of(2023, 7, 4, 15, 50);
18 |
19 | @DisplayName("Should include random OrderId when no OrderId exists")
20 | @Test
21 | void testShouldIncludeRandonOrderId_When_NoOrderIdExists() {
22 | // Given / Arrange
23 | try(MockedStatic mockedUuid = mockStatic(UUID.class)) {
24 | mockedUuid.when(UUID::randomUUID).thenReturn(defaultUuid);
25 |
26 | // When / Act
27 | Order result = service.createOrder("MacBook Pro", 2L, null);
28 |
29 | // Then / Assert
30 | assertEquals(defaultUuid.toString(), result.getId());
31 | }
32 | }
33 |
34 | @DisplayName("Should include current time when create a new Order")
35 | @Test
36 | void testShouldIncludeCurrentTime_When_CreateANewOrder() {
37 | // Given / Arrange
38 | try(MockedStatic mockedUuid = mockStatic(LocalDateTime.class)) {
39 | mockedUuid.when(LocalDateTime::now).thenReturn(defaultLocalDateTime);
40 |
41 | // When / Act
42 | Order result = service.createOrder("MacBook Pro", 2L, null);
43 |
44 | // Then / Assert
45 | assertEquals(defaultLocalDateTime, result.getCreationDate());
46 | }
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/mockito/staticwithparams/MyUtilsTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.staticwithparams;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.mockito.ArgumentMatchers.anyBoolean;
5 | import static org.mockito.ArgumentMatchers.eq;
6 | import static org.mockito.Mockito.mockStatic;
7 |
8 | import org.junit.jupiter.api.Test;
9 | import org.mockito.MockedStatic;
10 |
11 | class MyUtilsTest {
12 |
13 | @Test
14 | void shouldMockStaticMethodWithParams() {
15 | try(MockedStatic mockedStatic = mockStatic(MyUtils.class)){
16 | mockedStatic.when(
17 | () -> MyUtils.getWelcomeMessage(
18 | eq("Erudio"),
19 | anyBoolean())).thenReturn("Howdy Erudio!");
20 |
21 | String result = MyUtils.getWelcomeMessage("Erudio", false);
22 |
23 | assertEquals("Howdy Erudio!", result);
24 | }
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/S07_AdvancedConceptsofMockito/src/test/java/br/com/erudio/service/stubs/CourseServiceStub.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.service.stubs;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | import br.com.erudio.service.CourseService;
7 |
8 | public class CourseServiceStub implements CourseService{
9 |
10 | public List retrieveCourses(String student) {
11 | return Arrays.asList(
12 | "REST API's RESTFul do 0 à Azure com ASP.NET Core 5 e Docker",
13 | "Agile Desmistificado com Scrum, XP, Kanban e Trello",
14 | "Spotify Engineering Culture Desmistificado",
15 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Java e Docker",
16 | "Docker do Zero à Maestria - Contêinerização Desmistificada",
17 | "Docker para Amazon AWS Implante Apps Java e .NET com Travis CI",
18 | "Microsserviços do 0 com Spring Cloud, Spring Boot e Docker",
19 | "Arquitetura de Microsserviços do 0 com ASP.NET, .NET 6 e C#",
20 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Kotlin e Docker",
21 | "Kotlin para DEV's Java: Aprenda a Linguagem Padrão do Android",
22 | "Microsserviços do 0 com Spring Cloud, Kotlin e Docker"
23 | );
24 | }
25 |
26 | @Override
27 | public List doSomething(String student) {
28 | // TODO Auto-generated method stub
29 | return null;
30 | }
31 |
32 | @Override
33 | public void deleteCourse(String course) {
34 | // TODO Auto-generated method stub
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | br.com.erudio
4 | automated-tests-with-java-erudio
5 | 0.0.1-SNAPSHOT
6 |
7 | 19
8 | 5.9.2
9 | 5.2.0
10 | 2.2
11 | 19
12 | 19
13 | 3.10.1
14 | 3.0.0
15 | 0.8.9
16 |
17 |
18 |
19 |
20 | org.junit.jupiter
21 | junit-jupiter
22 | ${junit.version}
23 | test
24 |
25 |
26 |
27 | org.mockito
28 | mockito-junit-jupiter
29 | ${mockito.version}
30 | test
31 |
32 |
33 |
34 | org.mockito
35 | mockito-inline
36 | ${mockito.version}
37 | test
38 |
39 |
40 |
41 | org.hamcrest
42 | hamcrest
43 | ${hamcrest.version}
44 | test
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 | org.apache.maven.plugins
53 | maven-compiler-plugin
54 |
55 | ${java.version}
56 | ${java.version}
57 |
58 | ${maven.compiler.plugin.version}
59 |
60 |
61 | org.apache.maven.plugins
62 | maven-surefire-plugin
63 | ${maven.surefire.plugin.version}
64 |
65 | true
66 |
67 |
68 |
69 | org.apache.maven.plugins
70 | maven-surefire-report-plugin
71 | ${maven.surefire.plugin.version}
72 |
73 |
74 | test
75 |
76 | report
77 |
78 |
79 |
80 |
81 |
82 | org.jacoco
83 | jacoco-maven-plugin
84 | ${jacoco.plugin.version}
85 |
86 |
87 | prepare-agent
88 |
89 | prepare-agent
90 |
91 |
92 |
93 | report
94 | test
95 |
96 | report
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/main/java/br/com/erudio/business/CourseBusiness.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import br.com.erudio.service.CourseService;
7 |
8 | // CourseBusiness = SUT - System (Method) Under Test
9 | public class CourseBusiness {
10 |
11 | // CourseService is a Dependency
12 | private CourseService service;
13 |
14 | public CourseBusiness(CourseService service) {
15 | this.service = service;
16 | }
17 |
18 | public List retriveCoursesRelatedToSpring(String student) {
19 |
20 | var filteredCourses = new ArrayList();
21 | if("Foo Bar".equals(student)) return filteredCourses;
22 | var allCourses = service.retrieveCourses(student);
23 |
24 | for (String course : allCourses) {
25 | if (course.contains("Spring")) {
26 | filteredCourses.add(course);
27 | }
28 | }
29 |
30 | return filteredCourses;
31 | }
32 |
33 | public void deleteCoursesNotRelatedToSpring(String student) {
34 |
35 | var allCourses = service.retrieveCourses(student);
36 |
37 | for (String course : allCourses) {
38 | if (!course.contains("Spring")) {
39 | service.deleteCourse(course);
40 | }
41 | }
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/main/java/br/com/erudio/mockito/constructor/CheckoutService.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.constructor;
2 |
3 | import java.math.BigDecimal;
4 |
5 | public class CheckoutService {
6 |
7 | public BigDecimal purchaseProduct(String productName, String customerId) {
8 |
9 | // Any arbitrary implementation
10 | PaymentProcessor paymentProcessor = new PaymentProcessor();
11 | return paymentProcessor.chargeCustomer(customerId, BigDecimal.TEN);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/main/java/br/com/erudio/mockito/constructor/PaymentProcessor.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.constructor;
2 |
3 | import java.math.BigDecimal;
4 |
5 | public class PaymentProcessor {
6 |
7 | private boolean allowForeignCurrencies;
8 | private String fallbackOption;
9 | private BigDecimal taxRate;
10 |
11 | public PaymentProcessor() {
12 | this(false, "DEBIT", new BigDecimal("19.00"));
13 | }
14 |
15 | public PaymentProcessor(String fallbackOption, BigDecimal taxRate) {
16 | this(false, fallbackOption, taxRate);
17 | }
18 |
19 | public PaymentProcessor(boolean allowForeignCurrencies, String fallbackOption, BigDecimal taxRate) {
20 | this.allowForeignCurrencies = allowForeignCurrencies;
21 | this.fallbackOption = fallbackOption;
22 | this.taxRate = taxRate;
23 | }
24 |
25 | public BigDecimal chargeCustomer(String customerId, BigDecimal netPrice) {
26 |
27 | // Any arbitrary implementation
28 | System.out.println("About to charge customer: " + customerId);
29 | return BigDecimal.ZERO;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/main/java/br/com/erudio/mockito/services/Order.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.services;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | public class Order {
6 |
7 | private String id;
8 | private String productName;
9 | private Long amount;
10 | private LocalDateTime creationDate;
11 |
12 | public Order() {}
13 |
14 | public String getProductName() {
15 | return productName;
16 | }
17 |
18 | public void setProductName(String productName) {
19 | this.productName = productName;
20 | }
21 |
22 | public Long getAmount() {
23 | return amount;
24 | }
25 |
26 | public void setAmount(Long amount) {
27 | this.amount = amount;
28 | }
29 |
30 | public String getId() {
31 | return id;
32 | }
33 |
34 | public void setId(String id) {
35 | this.id = id;
36 | }
37 |
38 | public LocalDateTime getCreationDate() {
39 | return creationDate;
40 | }
41 |
42 | public void setCreationDate(LocalDateTime creationDate) {
43 | this.creationDate = creationDate;
44 | }
45 | }
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/main/java/br/com/erudio/mockito/services/OrderService.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.services;
2 |
3 | import java.time.LocalDateTime;
4 | import java.util.UUID;
5 |
6 | public class OrderService {
7 |
8 | public Order createOrder(String productName, Long amount, String orderID) {
9 |
10 | Order order = new Order();
11 |
12 | order.setId(orderID == null ? UUID.randomUUID().toString() : orderID);
13 | order.setCreationDate(LocalDateTime.now());
14 | order.setAmount(amount);
15 | order.setProductName(productName);
16 | return order;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/main/java/br/com/erudio/mockito/staticwithparams/MyUtils.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.staticwithparams;
2 |
3 | public class MyUtils {
4 |
5 | public static String getWelcomeMessage(String username, boolean isCustomer) {
6 |
7 | if (isCustomer) {
8 | return "Dear " + username;
9 | } else {
10 | return "Hello " + username;
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/main/java/br/com/erudio/service/CourseService.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.service;
2 |
3 | import java.util.List;
4 |
5 | public interface CourseService {
6 |
7 | public List retrieveCourses(String student);
8 | public List doSomething(String student);
9 | public void deleteCourse(String course);
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/business/CourseBusinessMockTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.mockito.Mockito.*;
5 |
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | import br.com.erudio.service.CourseService;
13 |
14 | class CourseBusinessMockTest {
15 |
16 | CourseService mockService;
17 | CourseBusiness business;
18 | List courses;
19 |
20 | @BeforeEach
21 | void setup() {
22 |
23 | // Given / Arrange
24 | mockService = mock(CourseService.class);
25 | business = new CourseBusiness(mockService);
26 |
27 | courses = Arrays.asList(
28 | "REST API's RESTFul do 0 à Azure com ASP.NET Core 5 e Docker",
29 | "Agile Desmistificado com Scrum, XP, Kanban e Trello",
30 | "Spotify Engineering Culture Desmistificado",
31 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Java e Docker",
32 | "Docker do Zero à Maestria - Contêinerização Desmistificada",
33 | "Docker para Amazon AWS Implante Apps Java e .NET com Travis CI",
34 | "Microsserviços do 0 com Spring Cloud, Spring Boot e Docker",
35 | "Arquitetura de Microsserviços do 0 com ASP.NET, .NET 6 e C#",
36 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Kotlin e Docker",
37 | "Kotlin para DEV's Java: Aprenda a Linguagem Padrão do Android",
38 | "Microsserviços do 0 com Spring Cloud, Kotlin e Docker"
39 | );
40 | }
41 |
42 | @Test
43 | void testCoursesRelatedToSpring_When_UsingAMock() {
44 |
45 | // Given / Arrange
46 | when(mockService.retrieveCourses("Leandro"))
47 | .thenReturn(courses);
48 |
49 | // When / Act
50 | var filteredCourses =
51 | business.retriveCoursesRelatedToSpring("Leandro");
52 |
53 | // Then / Assert
54 | assertEquals(4, filteredCourses.size());
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/business/CourseBusinessStubTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | import br.com.erudio.service.CourseService;
8 | import br.com.erudio.service.stubs.CourseServiceStub;
9 |
10 | class CourseBusinessStubTest {
11 |
12 | @Test
13 | void testCoursesRelatedToSpring_When_UsingAStub() {
14 |
15 | // Given / Arrange
16 | CourseService stubService = new CourseServiceStub();
17 | CourseBusiness business = new CourseBusiness(stubService);
18 |
19 | // When / Act
20 | var filteredCourses =
21 | business.retriveCoursesRelatedToSpring("Leandro");
22 |
23 | // Then / Assert
24 | assertEquals(4, filteredCourses.size());
25 | }
26 |
27 | @Test
28 | void testCoursesRelatedToSpring_When_UsingAFooBarStudent() {
29 |
30 | // Given / Arrange
31 | CourseService stubService = new CourseServiceStub();
32 | CourseBusiness business = new CourseBusiness(stubService);
33 |
34 | // When / Act
35 | var filteredCourses =
36 | business.retriveCoursesRelatedToSpring("Foo Bar");
37 |
38 | // Then / Assert
39 | assertEquals(0, filteredCourses.size());
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/business/ListTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 | import static org.mockito.Mockito.*;
5 |
6 | import java.util.List;
7 |
8 | import org.junit.jupiter.api.Test;
9 |
10 | public class ListTest {
11 |
12 | @Test
13 | void testMockingList_When_SizeIsCalled_ShouldReturn10() {
14 |
15 | // Given / Arrange
16 | List> list = mock(List.class);
17 | when(list.size()).thenReturn(10);
18 |
19 | // When / Act & Then / Assert
20 | assertEquals(10, list.size());
21 | assertEquals(10, list.size());
22 | assertEquals(10, list.size());
23 | }
24 |
25 | @Test
26 | void testMockingList_When_SizeIsCalled_ShouldReturnMultipleValues() {
27 |
28 | // Given / Arrange
29 | List> list = mock(List.class);
30 | when(list.size()).thenReturn(10).thenReturn(20);
31 |
32 | // When / Act & Then / Assert
33 | assertEquals(10, list.size());
34 | assertEquals(20, list.size());
35 | assertEquals(20, list.size());
36 | }
37 |
38 | @Test
39 | void testMockingList_When_GetIsCalled_ShouldReturnErudio() {
40 |
41 | // Given / Arrange
42 | var list = mock(List.class);
43 | when(list.get(0)).thenReturn("Erudio");
44 |
45 | // When / Act & Then / Assert
46 | assertEquals("Erudio", list.get(0));
47 | assertNull(list.get(1));
48 | }
49 |
50 | @Test
51 | void testMockingList_When_GetIsCalledWithArgumentMatcher_ShouldReturnErudio() {
52 |
53 | // Given / Arrange
54 | var list = mock(List.class);
55 |
56 | // If you are using argument matchers, all arguments
57 | // have to be provided by matchers.
58 | when(list.get(anyInt())).thenReturn("Erudio");
59 |
60 | // When / Act & Then / Assert
61 | assertEquals("Erudio", list.get(anyInt()));
62 | assertEquals("Erudio", list.get(anyInt()));
63 | }
64 |
65 | @Test
66 | void testMockingList_When_ThrowsAnException() {
67 |
68 | // Given / Arrange
69 | var list = mock(List.class);
70 |
71 | // If you are using argument matchers, all arguments
72 | // have to be provided by matchers.
73 | when(list.get(anyInt())).thenThrow(new RuntimeException("Foo Bar!!"));
74 |
75 | // When / Act & Then / Assert
76 | assertThrows(RuntimeException.class,
77 | () -> {
78 | // When / Act
79 | list.get(anyInt());},
80 | () -> "Should have throw an RuntimeException");
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/business/ListWithBDDTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.business;
2 |
3 | import static org.mockito.Mockito.*;
4 | import static org.mockito.BDDMockito.*;
5 |
6 | import static org.hamcrest.MatcherAssert.assertThat;
7 | import static org.hamcrest.Matchers.*;
8 | import static org.junit.jupiter.api.Assertions.assertNull;
9 | import static org.junit.jupiter.api.Assertions.assertThrows;
10 |
11 | import java.util.List;
12 |
13 | import org.junit.jupiter.api.Test;
14 |
15 | public class ListWithBDDTest {
16 |
17 | @Test
18 | void testMockingList_When_SizeIsCalled_ShouldReturn10() {
19 |
20 | // Given / Arrange
21 | List> list = mock(List.class);
22 | given(list.size()).willReturn(10);
23 |
24 | // When / Act & Then / Assert
25 | assertThat(list.size(), is(10));
26 | assertThat(list.size(), is(10));
27 | assertThat(list.size(), is(10));
28 | }
29 |
30 | @Test
31 | void testMockingList_When_SizeIsCalled_ShouldReturnMultipleValues() {
32 |
33 | // Given / Arrange
34 | List> list = mock(List.class);
35 | given(list.size()).willReturn(10).willReturn(20);
36 |
37 | // When / Act & Then / Assert
38 | assertThat(list.size(), is(10));
39 | assertThat(list.size(), is(20));
40 | assertThat(list.size(), is(20));
41 | }
42 |
43 | @Test
44 | void testMockingList_When_GetIsCalled_ShouldReturnErudio() {
45 |
46 | // Given / Arrange
47 | var list = mock(List.class);
48 | given(list.get(0)).willReturn("Erudio");
49 |
50 | // When / Act & Then / Assert
51 | assertThat(list.get(0), is("Erudio"));
52 | assertNull(list.get(1));
53 | }
54 |
55 | @Test
56 | void testMockingList_When_GetIsCalledWithArgumentMatcher_ShouldReturnErudio() {
57 |
58 | // Given / Arrange
59 | var list = mock(List.class);
60 |
61 | // If you are using argument matchers, all arguments
62 | // have to be provided by matchers.
63 | given(list.get(anyInt())).willReturn("Erudio");
64 |
65 | // When / Act & Then / Assert
66 | assertThat(list.get(anyInt()), is("Erudio"));
67 | assertThat(list.get(anyInt()), is("Erudio"));
68 | }
69 |
70 | @Test
71 | void testMockingList_When_ThrowsAnException() {
72 |
73 | // Given / Arrange
74 | var list = mock(List.class);
75 |
76 | // If you are using argument matchers, all arguments
77 | // have to be provided by matchers.
78 | given(list.get(anyInt())).willThrow(new RuntimeException("Foo Bar!!"));
79 |
80 | // When / Act & Then / Assert
81 | assertThrows(RuntimeException.class,
82 | () -> {
83 | // When / Act
84 | list.get(anyInt());},
85 | () -> "Should have throw an RuntimeException");
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/mockito/HamcrestMatchersTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | import static org.hamcrest.MatcherAssert.*;
7 | import static org.hamcrest.Matchers.*;
8 |
9 | import org.junit.jupiter.api.Test;
10 |
11 | class HamcrestMatchersTest {
12 |
13 | @Test
14 | void testHamcrestMatchers() {
15 | // Given
16 | List scores = Arrays.asList(99, 100, 101, 105);
17 |
18 | //When & Then
19 | assertThat(scores, hasSize(4));
20 | assertThat(scores, hasItems(100, 101));
21 | assertThat(scores, everyItem(greaterThan(98)));
22 | assertThat(scores, everyItem(lessThan(106)));
23 |
24 | // Check Strings
25 | assertThat("", is(emptyString()));
26 | assertThat(null, is(emptyOrNullString()));
27 |
28 | // Arrays
29 | Integer[] myArray = {1, 2, 3};
30 | assertThat(myArray, arrayWithSize(3));
31 | assertThat(myArray, arrayContaining(1, 2, 3));
32 | assertThat(myArray, arrayContainingInAnyOrder(3, 2, 1));
33 |
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/mockito/SpyTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.mockito.ArgumentMatchers.anyString;
5 | import static org.mockito.Mockito.mock;
6 | import static org.mockito.Mockito.never;
7 | import static org.mockito.Mockito.spy;
8 | import static org.mockito.Mockito.verify;
9 | import static org.mockito.Mockito.when;
10 |
11 | import java.util.ArrayList;
12 | import java.util.List;
13 |
14 | import org.junit.jupiter.api.Test;
15 |
16 | public class SpyTest {
17 |
18 | @Test
19 | void testV1() {
20 | // Given / Arrange
21 | List mockArrayList = spy(ArrayList.class);
22 |
23 | // When / Act & Then / Assert
24 | assertEquals(0, mockArrayList.size());
25 |
26 | when(mockArrayList.size()).thenReturn(5);
27 | mockArrayList.add("Foo-Bar");
28 |
29 | assertEquals(5, mockArrayList.size());
30 | }
31 |
32 | @Test
33 | void testV2() {
34 | // Given / Arrange
35 | List spyArrayList = spy(ArrayList.class);
36 |
37 | // When / Act & Then / Assert
38 | assertEquals(0, spyArrayList.size());
39 |
40 | spyArrayList.add("Foo-Bar");
41 | assertEquals(1, spyArrayList.size());
42 |
43 | spyArrayList.remove("Foo-Bar");
44 | assertEquals(0, spyArrayList.size());
45 | }
46 |
47 | @Test
48 | void testV3() {
49 | List spyArrayList = spy(ArrayList.class);
50 | assertEquals(0, spyArrayList.size());
51 | when(spyArrayList.size()).thenReturn(5);
52 | assertEquals(5, spyArrayList.size());
53 | }
54 |
55 | @Test
56 | void testV4() {
57 | List spyArrayList = spy(ArrayList.class);
58 | spyArrayList.add("Foo-Bar");
59 |
60 | verify(spyArrayList).add("Foo-Bar");
61 | // verify(spyArrayList, never()).remove("Foo-Bar");
62 | verify(spyArrayList, never()).remove(anyString());
63 | verify(spyArrayList, never()).clear();
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/mockito/constructor/CheckoutServiceTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.constructor;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.mockito.ArgumentMatchers.any;
5 | import static org.mockito.ArgumentMatchers.anyString;
6 | import static org.mockito.Mockito.mockConstruction;
7 | import static org.mockito.Mockito.when;
8 |
9 | import java.math.BigDecimal;
10 |
11 | import org.junit.jupiter.api.Test;
12 | import org.mockito.MockedConstruction;
13 |
14 | class CheckoutServiceTest {
15 |
16 | @Test
17 | void testMockObjectConstruction() {
18 |
19 | //Given
20 | try(MockedConstruction mocked =
21 | mockConstruction(PaymentProcessor.class,
22 | (mock, context) ->
23 | {
24 | when(mock.chargeCustomer(
25 | anyString(),
26 | any(BigDecimal.class))).thenReturn(BigDecimal.TEN);
27 | }))
28 | {
29 |
30 | CheckoutService service = new CheckoutService();
31 |
32 | //When
33 | BigDecimal result = service.purchaseProduct("MacBook Pro", "42");
34 |
35 | //Then
36 | assertEquals(BigDecimal.TEN, result);
37 | assertEquals(1, mocked.constructed().size());
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/mockito/constructor/PaymentProcessorTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.constructor;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.mockito.MockedConstruction;
5 | import org.mockito.Mockito;
6 |
7 | import java.math.BigDecimal;
8 |
9 | import static org.junit.jupiter.api.Assertions.assertEquals;
10 | import static org.mockito.ArgumentMatchers.anyString;
11 | import static org.mockito.Mockito.*;
12 |
13 | class PaymentProcessorTest {
14 |
15 | @Test
16 | void mockObjectConstruction() {
17 |
18 | // A real object of the PaymentProcessor is returned
19 | System.out.println(new PaymentProcessor().chargeCustomer("42", BigDecimal.valueOf(42)));
20 |
21 | try (MockedConstruction mocked = mockConstruction(PaymentProcessor.class)) {
22 |
23 | // Every object creation is returning a mock from now on
24 | PaymentProcessor paymentProcessor = new PaymentProcessor();
25 |
26 | when(paymentProcessor.chargeCustomer(anyString(), any(BigDecimal.class))).thenReturn(BigDecimal.TEN);
27 |
28 | assertEquals(BigDecimal.TEN, paymentProcessor.chargeCustomer("42", BigDecimal.valueOf(42)));
29 | }
30 |
31 | // A real object of the PaymentProcessor is returned
32 | System.out.println(new PaymentProcessor().chargeCustomer("42", BigDecimal.valueOf(42)));
33 | }
34 |
35 | @Test
36 | void mockDifferentObjectConstruction() {
37 | try (MockedConstruction mocked = Mockito.mockConstruction(PaymentProcessor.class)) {
38 |
39 | PaymentProcessor firstInstance = new PaymentProcessor("PayPal", BigDecimal.TEN);
40 | PaymentProcessor secondInstance = new PaymentProcessor(true, "PayPal", BigDecimal.TEN);
41 |
42 | when(firstInstance.chargeCustomer(anyString(), any(BigDecimal.class))).thenReturn(BigDecimal.TEN);
43 | when(secondInstance.chargeCustomer(anyString(), any(BigDecimal.class))).thenReturn(BigDecimal.TEN);
44 |
45 | assertEquals(BigDecimal.TEN, firstInstance.chargeCustomer("42", BigDecimal.valueOf(42)));
46 | assertEquals(BigDecimal.TEN, secondInstance.chargeCustomer("42", BigDecimal.valueOf(42)));
47 | assertEquals(2, mocked.constructed().size());
48 | }
49 | }
50 |
51 | @Test
52 | void mockDifferentObjectConstructionWithAnswer() {
53 | try (MockedConstruction mocked = Mockito.mockConstructionWithAnswer(PaymentProcessor.class,
54 | // Default answer for the first mock
55 | invocation -> new BigDecimal("500.00"),
56 | // Additional answer for all further mocks
57 | invocation -> new BigDecimal("42.00"))) {
58 |
59 | PaymentProcessor firstInstance = new PaymentProcessor();
60 | PaymentProcessor secondInstance = new PaymentProcessor();
61 | PaymentProcessor thirdInstance = new PaymentProcessor();
62 |
63 | assertEquals(new BigDecimal("500.00"), firstInstance.chargeCustomer("42", BigDecimal.ZERO));
64 | assertEquals(new BigDecimal("42.00"), secondInstance.chargeCustomer("42", BigDecimal.ZERO));
65 | assertEquals(new BigDecimal("42.00"), thirdInstance.chargeCustomer("42", BigDecimal.ZERO));
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/mockito/services/OrderServiceTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.services;
2 |
3 | import java.time.LocalDateTime;
4 | import java.util.UUID;
5 |
6 | import static org.junit.jupiter.api.Assertions.assertEquals;
7 | import static org.mockito.Mockito.*;
8 |
9 | import org.junit.jupiter.api.DisplayName;
10 | import org.junit.jupiter.api.Test;
11 | import org.mockito.MockedStatic;
12 |
13 | class OrderServiceTest {
14 |
15 | private final OrderService service = new OrderService();
16 | private final UUID defaultUuid = UUID.fromString("8d8b30e3-de52-4f1c-a71c-9905a8043dac");
17 | private final LocalDateTime defaultLocalDateTime = LocalDateTime.of(2023, 7, 4, 15, 50);
18 |
19 | @DisplayName("Should include random OrderId when no OrderId exists")
20 | @Test
21 | void testShouldIncludeRandonOrderId_When_NoOrderIdExists() {
22 | // Given / Arrange
23 | try(MockedStatic mockedUuid = mockStatic(UUID.class)) {
24 | mockedUuid.when(UUID::randomUUID).thenReturn(defaultUuid);
25 |
26 | // When / Act
27 | Order result = service.createOrder("MacBook Pro", 2L, null);
28 |
29 | // Then / Assert
30 | assertEquals(defaultUuid.toString(), result.getId());
31 | }
32 | }
33 |
34 | @DisplayName("Should include current time when create a new Order")
35 | @Test
36 | void testShouldIncludeCurrentTime_When_CreateANewOrder() {
37 | // Given / Arrange
38 | try(MockedStatic mockedUuid = mockStatic(LocalDateTime.class)) {
39 | mockedUuid.when(LocalDateTime::now).thenReturn(defaultLocalDateTime);
40 |
41 | // When / Act
42 | Order result = service.createOrder("MacBook Pro", 2L, null);
43 |
44 | // Then / Assert
45 | assertEquals(defaultLocalDateTime, result.getCreationDate());
46 | }
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/mockito/staticwithparams/MyUtilsTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.mockito.staticwithparams;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.mockito.ArgumentMatchers.anyBoolean;
5 | import static org.mockito.ArgumentMatchers.eq;
6 | import static org.mockito.Mockito.mockStatic;
7 |
8 | import org.junit.jupiter.api.Test;
9 | import org.mockito.MockedStatic;
10 |
11 | class MyUtilsTest {
12 |
13 | @Test
14 | void shouldMockStaticMethodWithParams() {
15 | try(MockedStatic mockedStatic = mockStatic(MyUtils.class)){
16 | mockedStatic.when(
17 | () -> MyUtils.getWelcomeMessage(
18 | eq("Erudio"),
19 | anyBoolean())).thenReturn("Howdy Erudio!");
20 |
21 | String result = MyUtils.getWelcomeMessage("Erudio", false);
22 |
23 | assertEquals("Howdy Erudio!", result);
24 | }
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/S08_CodeCoverage/src/test/java/br/com/erudio/service/stubs/CourseServiceStub.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.service.stubs;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | import br.com.erudio.service.CourseService;
7 |
8 | public class CourseServiceStub implements CourseService{
9 |
10 | public List retrieveCourses(String student) {
11 | return Arrays.asList(
12 | "REST API's RESTFul do 0 à Azure com ASP.NET Core 5 e Docker",
13 | "Agile Desmistificado com Scrum, XP, Kanban e Trello",
14 | "Spotify Engineering Culture Desmistificado",
15 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Java e Docker",
16 | "Docker do Zero à Maestria - Contêinerização Desmistificada",
17 | "Docker para Amazon AWS Implante Apps Java e .NET com Travis CI",
18 | "Microsserviços do 0 com Spring Cloud, Spring Boot e Docker",
19 | "Arquitetura de Microsserviços do 0 com ASP.NET, .NET 6 e C#",
20 | "REST API's RESTFul do 0 à AWS com Spring Boot 3 Kotlin e Docker",
21 | "Kotlin para DEV's Java: Aprenda a Linguagem Padrão do Android",
22 | "Microsserviços do 0 com Spring Cloud, Kotlin e Docker"
23 | );
24 | }
25 |
26 | @Override
27 | public List doSomething(String student) {
28 | // TODO Auto-generated method stub
29 | return null;
30 | }
31 |
32 | @Override
33 | public void deleteCourse(String course) {
34 | // TODO Auto-generated method stub
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/S09A_FirstStepsInJavawithSpringBoot/rest-with-spring-boot-and-java-erudio/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.0.1
9 |
10 |
11 | br.com.erudio
12 | rest-with-spring-boot-and-java-erudio
13 | 0.0.1-SNAPSHOT
14 | rest-with-spring-boot-and-java-erudio
15 | Demo project for Spring Boot
16 |
17 | 19
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 |
26 | org.springframework.boot
27 | spring-boot-devtools
28 | runtime
29 | true
30 |
31 |
32 | org.springframework.boot
33 | spring-boot-starter-test
34 | test
35 |
36 |
37 |
38 |
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-maven-plugin
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/S09A_FirstStepsInJavawithSpringBoot/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/Greeting.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | public class Greeting {
4 |
5 | private final long id;
6 | private final String content;
7 |
8 | public Greeting(long id, String content) {
9 | this.id = id;
10 | this.content = content;
11 | }
12 |
13 | public long getId() {
14 | return id;
15 | }
16 |
17 | public String getContent() {
18 | return content;
19 | }
20 | }
--------------------------------------------------------------------------------
/S09A_FirstStepsInJavawithSpringBoot/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/GreetingController.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import java.util.concurrent.atomic.AtomicLong;
4 |
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RequestParam;
7 | import org.springframework.web.bind.annotation.RestController;
8 |
9 | @RestController
10 | public class GreetingController {
11 |
12 | private static final String template = "Hello, %s!";
13 | private final AtomicLong counter = new AtomicLong();
14 |
15 | @RequestMapping("/greeting")
16 | public Greeting greeting(
17 | @RequestParam(value = "name", defaultValue = "World")
18 | String name) {
19 | return new Greeting(counter.incrementAndGet(), String.format(template, name));
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/S09A_FirstStepsInJavawithSpringBoot/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/Startup.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Startup {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Startup.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S09A_FirstStepsInJavawithSpringBoot/rest-with-spring-boot-and-java-erudio/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/S09A_FirstStepsInJavawithSpringBoot/rest-with-spring-boot-and-java-erudio/src/test/java/br/com/erudio/StartupTests.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class StartupTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S09B_ParametersAndExceptionHandler/rest-with-spring-boot-and-java-erudio/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.0.1
9 |
10 |
11 | br.com.erudio
12 | rest-with-spring-boot-and-java-erudio
13 | 0.0.1-SNAPSHOT
14 | rest-with-spring-boot-and-java-erudio
15 | Demo project for Spring Boot
16 |
17 | 19
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 |
26 | org.springframework.boot
27 | spring-boot-devtools
28 | runtime
29 | true
30 |
31 |
32 | org.springframework.boot
33 | spring-boot-starter-test
34 | test
35 |
36 |
37 |
38 |
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-maven-plugin
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/S09B_ParametersAndExceptionHandler/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/Startup.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Startup {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Startup.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S09B_ParametersAndExceptionHandler/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/controllers/MathController.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.controllers;
2 |
3 | import org.springframework.web.bind.annotation.PathVariable;
4 | import org.springframework.web.bind.annotation.RequestMapping;
5 | import org.springframework.web.bind.annotation.RequestMethod;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 | import br.com.erudio.converters.NumberConverter;
9 | import br.com.erudio.exceptions.UnsupportedMathOperationException;
10 | import br.com.erudio.math.SimpleMath;
11 |
12 | @RestController
13 | public class MathController {
14 |
15 | private SimpleMath math = new SimpleMath();
16 |
17 | @RequestMapping(value = "/sum/{numberOne}/{numberTwo}",
18 | method=RequestMethod.GET)
19 | public Double sum(
20 | @PathVariable(value = "numberOne") String numberOne,
21 | @PathVariable(value = "numberTwo") String numberTwo
22 | ) throws Exception{
23 |
24 | if(!NumberConverter.isNumeric(numberOne) || !NumberConverter.isNumeric(numberTwo)) {
25 | throw new UnsupportedMathOperationException("Please set a numeric value!");
26 | }
27 | return math.sum(NumberConverter.convertToDouble(numberOne), NumberConverter.convertToDouble(numberTwo));
28 | }
29 |
30 | @RequestMapping(value = "/subtraction/{numberOne}/{numberTwo}",
31 | method=RequestMethod.GET)
32 | public Double subtraction(
33 | @PathVariable(value = "numberOne") String numberOne,
34 | @PathVariable(value = "numberTwo") String numberTwo
35 | ) throws Exception{
36 |
37 | if(!NumberConverter.isNumeric(numberOne) || !NumberConverter.isNumeric(numberTwo)) {
38 | throw new UnsupportedMathOperationException("Please set a numeric value!");
39 | }
40 | return math.subtraction(NumberConverter.convertToDouble(numberOne), NumberConverter.convertToDouble(numberTwo));
41 | }
42 |
43 | @RequestMapping(value = "/multiplication/{numberOne}/{numberTwo}",
44 | method=RequestMethod.GET)
45 | public Double multiplication(
46 | @PathVariable(value = "numberOne") String numberOne,
47 | @PathVariable(value = "numberTwo") String numberTwo
48 | ) throws Exception{
49 |
50 | if(!NumberConverter.isNumeric(numberOne) || !NumberConverter.isNumeric(numberTwo)) {
51 | throw new UnsupportedMathOperationException("Please set a numeric value!");
52 | }
53 | return math.multiplication(NumberConverter.convertToDouble(numberOne), NumberConverter.convertToDouble(numberTwo));
54 | }
55 |
56 | @RequestMapping(value = "/division/{numberOne}/{numberTwo}",
57 | method=RequestMethod.GET)
58 | public Double division(
59 | @PathVariable(value = "numberOne") String numberOne,
60 | @PathVariable(value = "numberTwo") String numberTwo
61 | ) throws Exception{
62 |
63 | if(!NumberConverter.isNumeric(numberOne) || !NumberConverter.isNumeric(numberTwo)) {
64 | throw new UnsupportedMathOperationException("Please set a numeric value!");
65 | }
66 | return math.division(NumberConverter.convertToDouble(numberOne), NumberConverter.convertToDouble(numberTwo));
67 | }
68 |
69 | @RequestMapping(value = "/mean/{numberOne}/{numberTwo}",
70 | method=RequestMethod.GET)
71 | public Double mean(
72 | @PathVariable(value = "numberOne") String numberOne,
73 | @PathVariable(value = "numberTwo") String numberTwo
74 | ) throws Exception{
75 |
76 | if(!NumberConverter.isNumeric(numberOne) || !NumberConverter.isNumeric(numberTwo)) {
77 | throw new UnsupportedMathOperationException("Please set a numeric value!");
78 | }
79 | return math.mean(NumberConverter.convertToDouble(numberOne), NumberConverter.convertToDouble(numberTwo));
80 | }
81 |
82 | @RequestMapping(value = "/squareRoot/{number}",
83 | method=RequestMethod.GET)
84 | public Double squareRoot(
85 | @PathVariable(value = "number") String number
86 | ) throws Exception{
87 |
88 | if(!NumberConverter.isNumeric(number)) {
89 | throw new UnsupportedMathOperationException("Please set a numeric value!");
90 | }
91 | return math.squareRoot(NumberConverter.convertToDouble(number));
92 | }
93 | }
--------------------------------------------------------------------------------
/S09B_ParametersAndExceptionHandler/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/converters/NumberConverter.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.converters;
2 |
3 | public class NumberConverter {
4 |
5 | public static Double convertToDouble(String strNumber) {
6 | if (strNumber == null) return 0D;
7 | // BR 10,25 US 10.25
8 | String number = strNumber.replaceAll(",", ".");
9 | if (isNumeric(number)) return Double.parseDouble(number);
10 | return 0D;
11 | }
12 |
13 | public static boolean isNumeric(String strNumber) {
14 | if (strNumber == null) return false;
15 | String number = strNumber.replaceAll(",", ".");
16 | return number.matches("[-+]?[0-9]*\\.?[0-9]+");
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/S09B_ParametersAndExceptionHandler/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ExceptionResponse.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import java.io.Serializable;
4 | import java.util.Date;
5 |
6 | public class ExceptionResponse implements Serializable {
7 |
8 | private static final long serialVersionUID = 1L;
9 |
10 | private Date timestamp;
11 | private String message;
12 | private String details;
13 |
14 | public ExceptionResponse(Date timestamp, String message, String details) {
15 | this.timestamp = timestamp;
16 | this.message = message;
17 | this.details = details;
18 | }
19 |
20 | public Date getTimestamp() {
21 | return timestamp;
22 | }
23 |
24 | public String getMessage() {
25 | return message;
26 | }
27 |
28 | public String getDetails() {
29 | return details;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/S09B_ParametersAndExceptionHandler/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/UnsupportedMathOperationException.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.bind.annotation.ResponseStatus;
5 |
6 | @ResponseStatus(HttpStatus.BAD_REQUEST)
7 | public class UnsupportedMathOperationException extends RuntimeException{
8 |
9 | public UnsupportedMathOperationException(String ex) {
10 | super(ex);
11 | }
12 |
13 | private static final long serialVersionUID = 1L;
14 | }
--------------------------------------------------------------------------------
/S09B_ParametersAndExceptionHandler/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/handler/CustomizedResponseEntityExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions.handler;
2 |
3 | import java.util.Date;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.bind.annotation.RestController;
10 | import org.springframework.web.context.request.WebRequest;
11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
12 |
13 | import br.com.erudio.exceptions.ExceptionResponse;
14 | import br.com.erudio.exceptions.UnsupportedMathOperationException;
15 |
16 | @ControllerAdvice
17 | @RestController
18 | public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
19 |
20 | @ExceptionHandler(Exception.class)
21 | public final ResponseEntity handleAllExceptions(
22 | Exception ex, WebRequest request) {
23 |
24 | ExceptionResponse exceptionResponse = new ExceptionResponse(
25 | new Date(),
26 | ex.getMessage(),
27 | request.getDescription(false));
28 |
29 | return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
30 | }
31 |
32 | @ExceptionHandler(UnsupportedMathOperationException.class)
33 | public final ResponseEntity handleBadRequestExceptions(
34 | Exception ex, WebRequest request) {
35 |
36 | ExceptionResponse exceptionResponse = new ExceptionResponse(
37 | new Date(),
38 | ex.getMessage(),
39 | request.getDescription(false));
40 |
41 | return new ResponseEntity<>(exceptionResponse, HttpStatus.BAD_REQUEST);
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/S09B_ParametersAndExceptionHandler/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/math/SimpleMath.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.math;
2 |
3 | public class SimpleMath {
4 |
5 | public Double sum(Double numberOne, Double numberTwo) {
6 | return numberOne + numberTwo;
7 | }
8 |
9 | public Double subtraction(Double numberOne, Double numberTwo) {
10 | return numberOne - numberTwo;
11 | }
12 |
13 | public Double multiplication(Double numberOne, Double numberTwo) {
14 | return numberOne * numberTwo;
15 | }
16 |
17 | public Double division(Double numberOne, Double numberTwo) {
18 | return numberOne / numberTwo;
19 | }
20 |
21 | public Double mean(Double numberOne, Double numberTwo) {
22 | return (numberOne + numberTwo) / 2;
23 | }
24 |
25 | public Double squareRoot(Double number) {
26 | return Math.sqrt(number);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/S09B_ParametersAndExceptionHandler/rest-with-spring-boot-and-java-erudio/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/S09B_ParametersAndExceptionHandler/rest-with-spring-boot-and-java-erudio/src/test/java/br/com/erudio/StartupTests.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class StartupTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S09C_WorkingWithVerbs/rest-with-spring-boot-and-java-erudio/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.0.1
9 |
10 |
11 | br.com.erudio
12 | rest-with-spring-boot-and-java-erudio
13 | 0.0.1-SNAPSHOT
14 | rest-with-spring-boot-and-java-erudio
15 | Demo project for Spring Boot
16 |
17 | 19
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 |
26 | org.springframework.boot
27 | spring-boot-devtools
28 | runtime
29 | true
30 |
31 |
32 | org.springframework.boot
33 | spring-boot-starter-test
34 | test
35 |
36 |
37 |
38 |
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-maven-plugin
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/S09C_WorkingWithVerbs/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/Startup.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Startup {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Startup.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S09C_WorkingWithVerbs/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/controllers/PersonController.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.controllers;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.MediaType;
7 | import org.springframework.web.bind.annotation.PathVariable;
8 | import org.springframework.web.bind.annotation.RequestBody;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RequestMethod;
11 | import org.springframework.web.bind.annotation.RestController;
12 |
13 | import br.com.erudio.model.Person;
14 | import br.com.erudio.services.PersonServices;
15 |
16 | @RestController
17 | @RequestMapping("/person")
18 | public class PersonController {
19 |
20 | @Autowired
21 | private PersonServices service;
22 | ///private PersonServices service = new PersonServices();
23 |
24 | @RequestMapping(method=RequestMethod.GET,
25 | produces = MediaType.APPLICATION_JSON_VALUE)
26 | public List findAll() {
27 | return service.findAll();
28 | }
29 |
30 | @RequestMapping(value = "/{id}",
31 | method=RequestMethod.GET,
32 | produces = MediaType.APPLICATION_JSON_VALUE)
33 | public Person findById(@PathVariable(value = "id") String id) {
34 | return service.findById(id);
35 | }
36 |
37 | @RequestMapping(method=RequestMethod.POST,
38 | consumes = MediaType.APPLICATION_JSON_VALUE,
39 | produces = MediaType.APPLICATION_JSON_VALUE)
40 | public Person create(@RequestBody Person person) {
41 | return service.create(person);
42 | }
43 |
44 | @RequestMapping(method=RequestMethod.PUT,
45 | consumes = MediaType.APPLICATION_JSON_VALUE,
46 | produces = MediaType.APPLICATION_JSON_VALUE)
47 | public Person update(@RequestBody Person person) {
48 | return service.update(person);
49 | }
50 |
51 |
52 | @RequestMapping(value = "/{id}",
53 | method=RequestMethod.DELETE)
54 | public void delete(@PathVariable(value = "id") String id) {
55 | service.delete(id);
56 | }
57 | }
--------------------------------------------------------------------------------
/S09C_WorkingWithVerbs/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ExceptionResponse.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import java.io.Serializable;
4 | import java.util.Date;
5 |
6 | public class ExceptionResponse implements Serializable {
7 |
8 | private static final long serialVersionUID = 1L;
9 |
10 | private Date timestamp;
11 | private String message;
12 | private String details;
13 |
14 | public ExceptionResponse(Date timestamp, String message, String details) {
15 | this.timestamp = timestamp;
16 | this.message = message;
17 | this.details = details;
18 | }
19 |
20 | public Date getTimestamp() {
21 | return timestamp;
22 | }
23 |
24 | public String getMessage() {
25 | return message;
26 | }
27 |
28 | public String getDetails() {
29 | return details;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/S09C_WorkingWithVerbs/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/UnsupportedMathOperationException.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.bind.annotation.ResponseStatus;
5 |
6 | @ResponseStatus(HttpStatus.BAD_REQUEST)
7 | public class UnsupportedMathOperationException extends RuntimeException{
8 |
9 | public UnsupportedMathOperationException(String ex) {
10 | super(ex);
11 | }
12 |
13 | private static final long serialVersionUID = 1L;
14 | }
--------------------------------------------------------------------------------
/S09C_WorkingWithVerbs/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/handler/CustomizedResponseEntityExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions.handler;
2 |
3 | import java.util.Date;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.bind.annotation.RestController;
10 | import org.springframework.web.context.request.WebRequest;
11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
12 |
13 | import br.com.erudio.exceptions.ExceptionResponse;
14 | import br.com.erudio.exceptions.UnsupportedMathOperationException;
15 |
16 | @ControllerAdvice
17 | @RestController
18 | public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
19 |
20 | @ExceptionHandler(Exception.class)
21 | public final ResponseEntity handleAllExceptions(
22 | Exception ex, WebRequest request) {
23 |
24 | ExceptionResponse exceptionResponse = new ExceptionResponse(
25 | new Date(),
26 | ex.getMessage(),
27 | request.getDescription(false));
28 |
29 | return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
30 | }
31 |
32 | @ExceptionHandler(UnsupportedMathOperationException.class)
33 | public final ResponseEntity handleBadRequestExceptions(
34 | Exception ex, WebRequest request) {
35 |
36 | ExceptionResponse exceptionResponse = new ExceptionResponse(
37 | new Date(),
38 | ex.getMessage(),
39 | request.getDescription(false));
40 |
41 | return new ResponseEntity<>(exceptionResponse, HttpStatus.BAD_REQUEST);
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/S09C_WorkingWithVerbs/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/model/Person.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.model;
2 |
3 | import java.io.Serializable;
4 |
5 | public class Person implements Serializable {
6 |
7 | private static final long serialVersionUID = 1L;
8 |
9 | private Long id;
10 | private String firstName;
11 | private String lastName;
12 | private String address;
13 | private String gender;
14 |
15 | public Person() {}
16 |
17 | public Long getId() {
18 | return id;
19 | }
20 |
21 | public void setId(Long id) {
22 | this.id = id;
23 | }
24 |
25 | public String getFirstName() {
26 | return firstName;
27 | }
28 |
29 | public void setFirstName(String firstName) {
30 | this.firstName = firstName;
31 | }
32 |
33 | public String getLastName() {
34 | return lastName;
35 | }
36 |
37 | public void setLastName(String lastName) {
38 | this.lastName = lastName;
39 | }
40 |
41 | public String getAddress() {
42 | return address;
43 | }
44 |
45 | public void setAddress(String address) {
46 | this.address = address;
47 | }
48 |
49 | public String getGender() {
50 | return gender;
51 | }
52 |
53 | public void setGender(String gender) {
54 | this.gender = gender;
55 | }
56 |
57 | @Override
58 | public int hashCode() {
59 | final int prime = 31;
60 | int result = 1;
61 | result = prime * result + ((address == null) ? 0 : address.hashCode());
62 | result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
63 | result = prime * result + ((gender == null) ? 0 : gender.hashCode());
64 | result = prime * result + ((id == null) ? 0 : id.hashCode());
65 | result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
66 | return result;
67 | }
68 |
69 | @Override
70 | public boolean equals(Object obj) {
71 | if (this == obj)
72 | return true;
73 | if (obj == null)
74 | return false;
75 | if (getClass() != obj.getClass())
76 | return false;
77 | Person other = (Person) obj;
78 | if (address == null) {
79 | if (other.address != null)
80 | return false;
81 | } else if (!address.equals(other.address))
82 | return false;
83 | if (firstName == null) {
84 | if (other.firstName != null)
85 | return false;
86 | } else if (!firstName.equals(other.firstName))
87 | return false;
88 | if (gender == null) {
89 | if (other.gender != null)
90 | return false;
91 | } else if (!gender.equals(other.gender))
92 | return false;
93 | if (id == null) {
94 | if (other.id != null)
95 | return false;
96 | } else if (!id.equals(other.id))
97 | return false;
98 | if (lastName == null) {
99 | if (other.lastName != null)
100 | return false;
101 | } else if (!lastName.equals(other.lastName))
102 | return false;
103 | return true;
104 | }
105 | }
--------------------------------------------------------------------------------
/S09C_WorkingWithVerbs/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/services/PersonServices.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.services;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.concurrent.atomic.AtomicLong;
6 | import java.util.logging.Logger;
7 |
8 | import org.springframework.stereotype.Service;
9 |
10 | import br.com.erudio.model.Person;
11 |
12 | @Service
13 | public class PersonServices {
14 |
15 | private final AtomicLong counter = new AtomicLong();
16 |
17 | private Logger logger = Logger.getLogger(PersonServices.class.getName());
18 |
19 | public List findAll() {
20 |
21 | logger.info("Finding all people!");
22 |
23 | List persons = new ArrayList<>();
24 | for (int i = 0; i < 8; i++) {
25 | Person person = mockPerson(i);
26 | persons.add(person);
27 | }
28 | return persons;
29 | }
30 |
31 | public Person findById(String id) {
32 |
33 | logger.info("Finding one person!");
34 |
35 | Person person = new Person();
36 | person.setId(counter.incrementAndGet());
37 | person.setFirstName("Leandro");
38 | person.setLastName("Costa");
39 | person.setAddress("Uberlândia - Minas Gerais - Brasil");
40 | person.setGender("Male");
41 | return person;
42 | }
43 |
44 | public Person create(Person person) {
45 |
46 | logger.info("Creating one person!");
47 |
48 | return person;
49 | }
50 |
51 | public Person update(Person person) {
52 |
53 | logger.info("Updating one person!");
54 |
55 | return person;
56 | }
57 |
58 | public void delete(String id) {
59 |
60 | logger.info("Deleting one person!");
61 | }
62 |
63 | private Person mockPerson(int i) {
64 |
65 | Person person = new Person();
66 | person.setId(counter.incrementAndGet());
67 | person.setFirstName("Person name " + i);
68 | person.setLastName("Last name " + i);
69 | person.setAddress("Some address in Brasil " + i);
70 | person.setGender("Male");
71 | return person;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/S09C_WorkingWithVerbs/rest-with-spring-boot-and-java-erudio/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/S09C_WorkingWithVerbs/rest-with-spring-boot-and-java-erudio/src/test/java/br/com/erudio/StartupTests.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class StartupTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.0.1
9 |
10 |
11 | br.com.erudio
12 | rest-with-spring-boot-and-java-erudio
13 | 0.0.1-SNAPSHOT
14 | rest-with-spring-boot-and-java-erudio
15 | Demo project for Spring Boot
16 |
17 | 19
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-data-jpa
27 |
28 |
29 |
30 | mysql
31 | mysql-connector-java
32 |
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-starter-test
37 | test
38 |
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-devtools
43 | runtime
44 | true
45 |
46 |
47 |
48 |
49 |
50 |
51 | org.springframework.boot
52 | spring-boot-maven-plugin
53 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/Startup.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Startup {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Startup.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/controllers/PersonController.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.controllers;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.MediaType;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.DeleteMapping;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PostMapping;
12 | import org.springframework.web.bind.annotation.PutMapping;
13 | import org.springframework.web.bind.annotation.RequestBody;
14 | import org.springframework.web.bind.annotation.RequestMapping;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import br.com.erudio.model.Person;
18 | import br.com.erudio.services.PersonServices;
19 |
20 | @RestController
21 | @RequestMapping("/person")
22 | public class PersonController {
23 |
24 | @Autowired
25 | private PersonServices service;
26 |
27 | @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
28 | public List findAll() {
29 | return service.findAll();
30 | }
31 |
32 | @GetMapping(value = "/{id}",
33 | produces = MediaType.APPLICATION_JSON_VALUE)
34 | public Person findById(@PathVariable(value = "id") Long id) {
35 | return service.findById(id);
36 | }
37 |
38 | @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
39 | produces = MediaType.APPLICATION_JSON_VALUE)
40 | public Person create(@RequestBody Person person) {
41 | return service.create(person);
42 | }
43 |
44 | @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
45 | produces = MediaType.APPLICATION_JSON_VALUE)
46 | public Person update(@RequestBody Person person) {
47 | return service.update(person);
48 | }
49 |
50 |
51 | @DeleteMapping(value = "/{id}")
52 | public ResponseEntity> delete(@PathVariable(value = "id") Long id) {
53 | service.delete(id);
54 | return ResponseEntity.noContent().build();
55 | }
56 | }
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ExceptionResponse.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import java.io.Serializable;
4 | import java.util.Date;
5 |
6 | public class ExceptionResponse implements Serializable {
7 |
8 | private static final long serialVersionUID = 1L;
9 |
10 | private Date timestamp;
11 | private String message;
12 | private String details;
13 |
14 | public ExceptionResponse(Date timestamp, String message, String details) {
15 | this.timestamp = timestamp;
16 | this.message = message;
17 | this.details = details;
18 | }
19 |
20 | public Date getTimestamp() {
21 | return timestamp;
22 | }
23 |
24 | public String getMessage() {
25 | return message;
26 | }
27 |
28 | public String getDetails() {
29 | return details;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ResourceNotFoundException.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.bind.annotation.ResponseStatus;
5 |
6 | @ResponseStatus(HttpStatus.NOT_FOUND)
7 | public class ResourceNotFoundException extends RuntimeException{
8 |
9 | private static final long serialVersionUID = 1L;
10 |
11 | public ResourceNotFoundException(String ex) {
12 | super(ex);
13 | }
14 | }
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/handler/CustomizedResponseEntityExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions.handler;
2 |
3 | import java.util.Date;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.bind.annotation.RestController;
10 | import org.springframework.web.context.request.WebRequest;
11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
12 |
13 | import br.com.erudio.exceptions.ExceptionResponse;
14 | import br.com.erudio.exceptions.ResourceNotFoundException;
15 |
16 | @ControllerAdvice
17 | @RestController
18 | public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
19 |
20 | @ExceptionHandler(Exception.class)
21 | public final ResponseEntity handleAllExceptions(
22 | Exception ex, WebRequest request) {
23 |
24 | ExceptionResponse exceptionResponse = new ExceptionResponse(
25 | new Date(),
26 | ex.getMessage(),
27 | request.getDescription(false));
28 |
29 | return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
30 | }
31 |
32 | @ExceptionHandler(ResourceNotFoundException.class)
33 | public final ResponseEntity handleNotFoundExceptions(
34 | Exception ex, WebRequest request) {
35 |
36 | ExceptionResponse exceptionResponse = new ExceptionResponse(
37 | new Date(),
38 | ex.getMessage(),
39 | request.getDescription(false));
40 |
41 | return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/model/Person.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.model;
2 |
3 | import java.io.Serializable;
4 |
5 | import jakarta.persistence.Column;
6 | import jakarta.persistence.Entity;
7 | import jakarta.persistence.GeneratedValue;
8 | import jakarta.persistence.GenerationType;
9 | import jakarta.persistence.Id;
10 | import jakarta.persistence.Table;
11 |
12 | @Entity
13 | @Table(name = "person")
14 | public class Person implements Serializable {
15 |
16 | private static final long serialVersionUID = 1L;
17 |
18 | @Id
19 | @GeneratedValue(strategy = GenerationType.IDENTITY)
20 | private Long id;
21 |
22 | @Column(name = "first_name", nullable = false, length = 80)
23 | private String firstName;
24 |
25 | @Column(name = "last_name", nullable = false, length = 80)
26 | private String lastName;
27 |
28 | @Column(nullable = false, length = 100)
29 | private String address;
30 |
31 | @Column(nullable = false, length = 6)
32 | private String gender;
33 |
34 | public Person() {}
35 |
36 | public Long getId() {
37 | return id;
38 | }
39 |
40 | public void setId(Long id) {
41 | this.id = id;
42 | }
43 |
44 | public String getFirstName() {
45 | return firstName;
46 | }
47 |
48 | public void setFirstName(String firstName) {
49 | this.firstName = firstName;
50 | }
51 |
52 | public String getLastName() {
53 | return lastName;
54 | }
55 |
56 | public void setLastName(String lastName) {
57 | this.lastName = lastName;
58 | }
59 |
60 | public String getAddress() {
61 | return address;
62 | }
63 |
64 | public void setAddress(String address) {
65 | this.address = address;
66 | }
67 |
68 | public String getGender() {
69 | return gender;
70 | }
71 |
72 | public void setGender(String gender) {
73 | this.gender = gender;
74 | }
75 |
76 | @Override
77 | public int hashCode() {
78 | final int prime = 31;
79 | int result = 1;
80 | result = prime * result + ((address == null) ? 0 : address.hashCode());
81 | result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
82 | result = prime * result + ((gender == null) ? 0 : gender.hashCode());
83 | result = prime * result + ((id == null) ? 0 : id.hashCode());
84 | result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
85 | return result;
86 | }
87 |
88 | @Override
89 | public boolean equals(Object obj) {
90 | if (this == obj)
91 | return true;
92 | if (obj == null)
93 | return false;
94 | if (getClass() != obj.getClass())
95 | return false;
96 | Person other = (Person) obj;
97 | if (address == null) {
98 | if (other.address != null)
99 | return false;
100 | } else if (!address.equals(other.address))
101 | return false;
102 | if (firstName == null) {
103 | if (other.firstName != null)
104 | return false;
105 | } else if (!firstName.equals(other.firstName))
106 | return false;
107 | if (gender == null) {
108 | if (other.gender != null)
109 | return false;
110 | } else if (!gender.equals(other.gender))
111 | return false;
112 | if (id == null) {
113 | if (other.id != null)
114 | return false;
115 | } else if (!id.equals(other.id))
116 | return false;
117 | if (lastName == null) {
118 | if (other.lastName != null)
119 | return false;
120 | } else if (!lastName.equals(other.lastName))
121 | return false;
122 | return true;
123 | }
124 | }
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/repositories/PersonRepository.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.repositories;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 |
5 | import br.com.erudio.model.Person;
6 |
7 | public interface PersonRepository extends JpaRepository {}
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/services/PersonServices.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.services;
2 |
3 | import java.util.List;
4 | import java.util.logging.Logger;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Service;
8 |
9 | import br.com.erudio.exceptions.ResourceNotFoundException;
10 | import br.com.erudio.model.Person;
11 | import br.com.erudio.repositories.PersonRepository;
12 |
13 | @Service
14 | public class PersonServices {
15 |
16 | private Logger logger = Logger.getLogger(PersonServices.class.getName());
17 |
18 | @Autowired
19 | PersonRepository repository;
20 |
21 | public List findAll() {
22 |
23 | logger.info("Finding all people!");
24 |
25 | return repository.findAll();
26 | }
27 |
28 | public Person findById(Long id) {
29 |
30 | logger.info("Finding one person!");
31 |
32 | return repository.findById(id)
33 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
34 | }
35 |
36 | public Person create(Person person) {
37 |
38 | logger.info("Creating one person!");
39 |
40 | return repository.save(person);
41 | }
42 |
43 | public Person update(Person person) {
44 |
45 | logger.info("Updating one person!");
46 |
47 | var entity = repository.findById(person.getId())
48 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
49 |
50 | entity.setFirstName(person.getFirstName());
51 | entity.setLastName(person.getLastName());
52 | entity.setAddress(person.getAddress());
53 | entity.setGender(person.getGender());
54 |
55 | return repository.save(person);
56 | }
57 |
58 | public void delete(Long id) {
59 |
60 | logger.info("Deleting one person!");
61 |
62 | var entity = repository.findById(id)
63 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
64 | repository.delete(entity);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | datasource:
3 | driver-class-name: com.mysql.cj.jdbc.Driver
4 | url: jdbc:mysql://localhost:3306/rest_with_spring_boot_erudio?useTimezone=true&serverTimezone=UTC
5 | username: root
6 | password: admin123
7 | jpa:
8 | hibernate:
9 | ddl-auto: update
10 | properties:
11 | hibernate:
12 | dialect: org.hibernate.dialect.MySQL8Dialect
13 | show-sql: false
--------------------------------------------------------------------------------
/S09D_ConnectingToMySQL/rest-with-spring-boot-and-java-erudio/src/test/java/br/com/erudio/StartupTests.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class StartupTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.0.5
9 |
10 |
11 | br.com.erudio
12 | rest-with-spring-boot-and-java-erudio
13 | 0.0.1-SNAPSHOT
14 | rest-with-spring-boot-and-java-erudio
15 | Demo project for Spring Boot
16 |
17 | 19
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-data-jpa
27 |
28 |
29 |
30 | com.mysql
31 | mysql-connector-j
32 | runtime
33 |
34 |
35 |
36 | com.h2database
37 | h2
38 | test
39 |
40 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-test
44 | test
45 |
46 |
47 |
48 | org.springframework.boot
49 | spring-boot-devtools
50 | runtime
51 | true
52 |
53 |
54 |
55 |
56 |
57 |
58 | org.springframework.boot
59 | spring-boot-maven-plugin
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/Startup.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Startup {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Startup.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/controllers/PersonController.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.controllers;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.MediaType;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.DeleteMapping;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PostMapping;
12 | import org.springframework.web.bind.annotation.PutMapping;
13 | import org.springframework.web.bind.annotation.RequestBody;
14 | import org.springframework.web.bind.annotation.RequestMapping;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import br.com.erudio.model.Person;
18 | import br.com.erudio.services.PersonServices;
19 |
20 | @RestController
21 | @RequestMapping("/person")
22 | public class PersonController {
23 |
24 | @Autowired
25 | private PersonServices service;
26 |
27 | @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
28 | public List findAll() {
29 | return service.findAll();
30 | }
31 |
32 | @GetMapping(value = "/{id}",
33 | produces = MediaType.APPLICATION_JSON_VALUE)
34 | public Person findById(@PathVariable(value = "id") Long id) {
35 | return service.findById(id);
36 | }
37 |
38 | @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
39 | produces = MediaType.APPLICATION_JSON_VALUE)
40 | public Person create(@RequestBody Person person) {
41 | return service.create(person);
42 | }
43 |
44 | @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
45 | produces = MediaType.APPLICATION_JSON_VALUE)
46 | public Person update(@RequestBody Person person) {
47 | return service.update(person);
48 | }
49 |
50 |
51 | @DeleteMapping(value = "/{id}")
52 | public ResponseEntity> delete(@PathVariable(value = "id") Long id) {
53 | service.delete(id);
54 | return ResponseEntity.noContent().build();
55 | }
56 | }
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ExceptionResponse.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import java.io.Serializable;
4 | import java.util.Date;
5 |
6 | public class ExceptionResponse implements Serializable {
7 |
8 | private static final long serialVersionUID = 1L;
9 |
10 | private Date timestamp;
11 | private String message;
12 | private String details;
13 |
14 | public ExceptionResponse(Date timestamp, String message, String details) {
15 | this.timestamp = timestamp;
16 | this.message = message;
17 | this.details = details;
18 | }
19 |
20 | public Date getTimestamp() {
21 | return timestamp;
22 | }
23 |
24 | public String getMessage() {
25 | return message;
26 | }
27 |
28 | public String getDetails() {
29 | return details;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ResourceNotFoundException.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.bind.annotation.ResponseStatus;
5 |
6 | @ResponseStatus(HttpStatus.NOT_FOUND)
7 | public class ResourceNotFoundException extends RuntimeException{
8 |
9 | private static final long serialVersionUID = 1L;
10 |
11 | public ResourceNotFoundException(String ex) {
12 | super(ex);
13 | }
14 | }
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/handler/CustomizedResponseEntityExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions.handler;
2 |
3 | import java.util.Date;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.bind.annotation.RestController;
10 | import org.springframework.web.context.request.WebRequest;
11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
12 |
13 | import br.com.erudio.exceptions.ExceptionResponse;
14 | import br.com.erudio.exceptions.ResourceNotFoundException;
15 |
16 | @ControllerAdvice
17 | @RestController
18 | public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
19 |
20 | @ExceptionHandler(Exception.class)
21 | public final ResponseEntity handleAllExceptions(
22 | Exception ex, WebRequest request) {
23 |
24 | ExceptionResponse exceptionResponse = new ExceptionResponse(
25 | new Date(),
26 | ex.getMessage(),
27 | request.getDescription(false));
28 |
29 | return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
30 | }
31 |
32 | @ExceptionHandler(ResourceNotFoundException.class)
33 | public final ResponseEntity handleNotFoundExceptions(
34 | Exception ex, WebRequest request) {
35 |
36 | ExceptionResponse exceptionResponse = new ExceptionResponse(
37 | new Date(),
38 | ex.getMessage(),
39 | request.getDescription(false));
40 |
41 | return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/repositories/PersonRepository.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.repositories;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.data.jpa.repository.Query;
7 | import org.springframework.data.repository.query.Param;
8 |
9 | import br.com.erudio.model.Person;
10 |
11 | public interface PersonRepository extends JpaRepository {
12 |
13 | Optional findByEmail(String email);
14 |
15 | // Define custom query using JPQL with index parameters
16 | @Query("select p from Person p where p.firstName =?1 and p.lastName =?2")
17 | Person findByJPQL(String firstName, String lastName);
18 |
19 | // Define custom query using JPQL with named parameters
20 | @Query("select p from Person p where p.firstName =:firstName and p.lastName =:lastName")
21 | Person findByJPQLNamedParameters(
22 | @Param("firstName") String firstName,
23 | @Param("lastName") String lastName);
24 |
25 | // Define custom query using Native SQL with index parameters
26 | @Query(value = "select * from person p where p.first_name =?1 and p.last_name =?2", nativeQuery = true)
27 | Person findByNativeSQL(String firstName, String lastName);
28 |
29 | // Define custom query using Native SQL with named parameters
30 | @Query(value = "select * from person p where p.first_name =:firstName and p.last_name =:lastName", nativeQuery = true)
31 | Person findByNativeSQLwithNamedParameters(
32 | @Param("firstName") String firstName,
33 | @Param("lastName") String lastName);
34 | }
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/services/PersonServices.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.services;
2 |
3 | import java.util.List;
4 | import java.util.logging.Logger;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Service;
8 |
9 | import br.com.erudio.exceptions.ResourceNotFoundException;
10 | import br.com.erudio.model.Person;
11 | import br.com.erudio.repositories.PersonRepository;
12 |
13 | @Service
14 | public class PersonServices {
15 |
16 | private Logger logger = Logger.getLogger(PersonServices.class.getName());
17 |
18 | @Autowired
19 | PersonRepository repository;
20 |
21 | public List findAll() {
22 |
23 | logger.info("Finding all people!");
24 |
25 | return repository.findAll();
26 | }
27 |
28 | public Person findById(Long id) {
29 |
30 | logger.info("Finding one person!");
31 |
32 | return repository.findById(id)
33 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
34 | }
35 |
36 | public Person create(Person person) {
37 |
38 | logger.info("Creating one person!");
39 |
40 | return repository.save(person);
41 | }
42 |
43 | public Person update(Person person) {
44 |
45 | logger.info("Updating one person!");
46 |
47 | var entity = repository.findById(person.getId())
48 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
49 |
50 | entity.setFirstName(person.getFirstName());
51 | entity.setLastName(person.getLastName());
52 | entity.setAddress(person.getAddress());
53 | entity.setGender(person.getGender());
54 |
55 | return repository.save(person);
56 | }
57 |
58 | public void delete(Long id) {
59 |
60 | logger.info("Deleting one person!");
61 |
62 | var entity = repository.findById(id)
63 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
64 | repository.delete(entity);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | datasource:
3 | driver-class-name: com.mysql.cj.jdbc.Driver
4 | url: jdbc:mysql://localhost:3306/rest_with_spring_boot_erudio?useTimezone=true&serverTimezone=UTC
5 | username: root
6 | password: admin123
7 | jpa:
8 | hibernate:
9 | ddl-auto: update
10 | properties:
11 | hibernate:
12 | dialect: org.hibernate.dialect.MySQL8Dialect
13 | show-sql: false
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/src/test/java/br/com/erudio/StartupTests.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class StartupTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S10_TestingRepositories/rest-with-spring-boot-and-java-erudio/src/test/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | datasource:
3 | url: jdbc:h2:~/testdb;DB_CLOSE_ON_EXIT=FALSE
4 | username: sa
5 | password:
6 | driver-class-name: org.h2.Driver
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.0.5
9 |
10 |
11 | br.com.erudio
12 | rest-with-spring-boot-and-java-erudio
13 | 0.0.1-SNAPSHOT
14 | rest-with-spring-boot-and-java-erudio
15 | Demo project for Spring Boot
16 |
17 | 19
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-data-jpa
27 |
28 |
29 |
30 | com.mysql
31 | mysql-connector-j
32 | runtime
33 |
34 |
35 |
36 | com.h2database
37 | h2
38 | test
39 |
40 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-test
44 | test
45 |
46 |
47 |
48 | org.springframework.boot
49 | spring-boot-devtools
50 | runtime
51 | true
52 |
53 |
54 |
55 |
56 |
57 |
58 | org.springframework.boot
59 | spring-boot-maven-plugin
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/Startup.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Startup {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Startup.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/controllers/PersonController.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.controllers;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.MediaType;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.DeleteMapping;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PostMapping;
12 | import org.springframework.web.bind.annotation.PutMapping;
13 | import org.springframework.web.bind.annotation.RequestBody;
14 | import org.springframework.web.bind.annotation.RequestMapping;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import br.com.erudio.model.Person;
18 | import br.com.erudio.services.PersonServices;
19 |
20 | @RestController
21 | @RequestMapping("/person")
22 | public class PersonController {
23 |
24 | @Autowired
25 | private PersonServices service;
26 |
27 | @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
28 | public List findAll() {
29 | return service.findAll();
30 | }
31 |
32 | @GetMapping(value = "/{id}",
33 | produces = MediaType.APPLICATION_JSON_VALUE)
34 | public Person findById(@PathVariable(value = "id") Long id) {
35 | return service.findById(id);
36 | }
37 |
38 | @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
39 | produces = MediaType.APPLICATION_JSON_VALUE)
40 | public Person create(@RequestBody Person person) {
41 | return service.create(person);
42 | }
43 |
44 | @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
45 | produces = MediaType.APPLICATION_JSON_VALUE)
46 | public Person update(@RequestBody Person person) {
47 | return service.update(person);
48 | }
49 |
50 |
51 | @DeleteMapping(value = "/{id}")
52 | public ResponseEntity> delete(@PathVariable(value = "id") Long id) {
53 | service.delete(id);
54 | return ResponseEntity.noContent().build();
55 | }
56 | }
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ExceptionResponse.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import java.io.Serializable;
4 | import java.util.Date;
5 |
6 | public class ExceptionResponse implements Serializable {
7 |
8 | private static final long serialVersionUID = 1L;
9 |
10 | private Date timestamp;
11 | private String message;
12 | private String details;
13 |
14 | public ExceptionResponse(Date timestamp, String message, String details) {
15 | this.timestamp = timestamp;
16 | this.message = message;
17 | this.details = details;
18 | }
19 |
20 | public Date getTimestamp() {
21 | return timestamp;
22 | }
23 |
24 | public String getMessage() {
25 | return message;
26 | }
27 |
28 | public String getDetails() {
29 | return details;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ResourceNotFoundException.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.bind.annotation.ResponseStatus;
5 |
6 | @ResponseStatus(HttpStatus.NOT_FOUND)
7 | public class ResourceNotFoundException extends RuntimeException{
8 |
9 | private static final long serialVersionUID = 1L;
10 |
11 | public ResourceNotFoundException(String ex) {
12 | super(ex);
13 | }
14 | }
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/handler/CustomizedResponseEntityExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions.handler;
2 |
3 | import java.util.Date;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.bind.annotation.RestController;
10 | import org.springframework.web.context.request.WebRequest;
11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
12 |
13 | import br.com.erudio.exceptions.ExceptionResponse;
14 | import br.com.erudio.exceptions.ResourceNotFoundException;
15 |
16 | @ControllerAdvice
17 | @RestController
18 | public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
19 |
20 | @ExceptionHandler(Exception.class)
21 | public final ResponseEntity handleAllExceptions(
22 | Exception ex, WebRequest request) {
23 |
24 | ExceptionResponse exceptionResponse = new ExceptionResponse(
25 | new Date(),
26 | ex.getMessage(),
27 | request.getDescription(false));
28 |
29 | return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
30 | }
31 |
32 | @ExceptionHandler(ResourceNotFoundException.class)
33 | public final ResponseEntity handleNotFoundExceptions(
34 | Exception ex, WebRequest request) {
35 |
36 | ExceptionResponse exceptionResponse = new ExceptionResponse(
37 | new Date(),
38 | ex.getMessage(),
39 | request.getDescription(false));
40 |
41 | return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/repositories/PersonRepository.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.repositories;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.data.jpa.repository.Query;
7 | import org.springframework.data.repository.query.Param;
8 |
9 | import br.com.erudio.model.Person;
10 |
11 | public interface PersonRepository extends JpaRepository {
12 |
13 | Optional findByEmail(String email);
14 |
15 | // Define custom query using JPQL with index parameters
16 | @Query("select p from Person p where p.firstName =?1 and p.lastName =?2")
17 | Person findByJPQL(String firstName, String lastName);
18 |
19 | // Define custom query using JPQL with named parameters
20 | @Query("select p from Person p where p.firstName =:firstName and p.lastName =:lastName")
21 | Person findByJPQLNamedParameters(
22 | @Param("firstName") String firstName,
23 | @Param("lastName") String lastName);
24 |
25 | // Define custom query using Native SQL with index parameters
26 | @Query(value = "select * from person p where p.first_name =?1 and p.last_name =?2", nativeQuery = true)
27 | Person findByNativeSQL(String firstName, String lastName);
28 |
29 | // Define custom query using Native SQL with named parameters
30 | @Query(value = "select * from person p where p.first_name =:firstName and p.last_name =:lastName", nativeQuery = true)
31 | Person findByNativeSQLwithNamedParameters(
32 | @Param("firstName") String firstName,
33 | @Param("lastName") String lastName);
34 | }
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/services/PersonServices.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.services;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 | import java.util.logging.Logger;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.stereotype.Service;
9 |
10 | import br.com.erudio.exceptions.ResourceNotFoundException;
11 | import br.com.erudio.model.Person;
12 | import br.com.erudio.repositories.PersonRepository;
13 |
14 | @Service
15 | public class PersonServices {
16 |
17 | private Logger logger = Logger.getLogger(PersonServices.class.getName());
18 |
19 | @Autowired
20 | PersonRepository repository;
21 |
22 | public List findAll() {
23 |
24 | logger.info("Finding all people!");
25 |
26 | return repository.findAll();
27 | }
28 |
29 | public Person findById(Long id) {
30 |
31 | logger.info("Finding one person!");
32 |
33 | return repository.findById(id)
34 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
35 | }
36 |
37 | public Person create(Person person) {
38 |
39 | logger.info("Creating one person!");
40 |
41 | Optional savedPerson = repository.findByEmail(person.getEmail());
42 | if(savedPerson.isPresent()) {
43 | throw new ResourceNotFoundException(
44 | "Person already exist with given e-Mail: " + person.getEmail());
45 | }
46 | return repository.save(person);
47 | }
48 |
49 | public Person update(Person person) {
50 |
51 | logger.info("Updating one person!");
52 |
53 | var entity = repository.findById(person.getId())
54 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
55 |
56 | entity.setFirstName(person.getFirstName());
57 | entity.setLastName(person.getLastName());
58 | entity.setAddress(person.getAddress());
59 | entity.setGender(person.getGender());
60 |
61 | return repository.save(person);
62 | }
63 |
64 | public void delete(Long id) {
65 |
66 | logger.info("Deleting one person!");
67 |
68 | var entity = repository.findById(id)
69 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
70 | repository.delete(entity);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | datasource:
3 | driver-class-name: com.mysql.cj.jdbc.Driver
4 | url: jdbc:mysql://localhost:3306/rest_with_spring_boot_erudio?useTimezone=true&serverTimezone=UTC
5 | username: root
6 | password: admin123
7 | jpa:
8 | hibernate:
9 | ddl-auto: update
10 | properties:
11 | hibernate:
12 | dialect: org.hibernate.dialect.MySQL8Dialect
13 | show-sql: false
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/src/test/java/br/com/erudio/StartupTests.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class StartupTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S11_TestingServices/rest-with-spring-boot-and-java-erudio/src/test/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | datasource:
3 | url: jdbc:h2:~/testdb;DB_CLOSE_ON_EXIT=FALSE
4 | username: sa
5 | password:
6 | driver-class-name: org.h2.Driver
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.0.5
9 |
10 |
11 | br.com.erudio
12 | rest-with-spring-boot-and-java-erudio
13 | 0.0.1-SNAPSHOT
14 | rest-with-spring-boot-and-java-erudio
15 | Demo project for Spring Boot
16 |
17 | 19
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-data-jpa
27 |
28 |
29 |
30 | com.mysql
31 | mysql-connector-j
32 | runtime
33 |
34 |
35 |
36 | com.h2database
37 | h2
38 | test
39 |
40 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-test
44 | test
45 |
46 |
47 |
48 | org.springframework.boot
49 | spring-boot-devtools
50 | runtime
51 | true
52 |
53 |
54 |
55 |
56 |
57 |
58 | org.springframework.boot
59 | spring-boot-maven-plugin
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/Startup.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Startup {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Startup.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/controllers/PersonController.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.controllers;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.MediaType;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.DeleteMapping;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PostMapping;
12 | import org.springframework.web.bind.annotation.PutMapping;
13 | import org.springframework.web.bind.annotation.RequestBody;
14 | import org.springframework.web.bind.annotation.RequestMapping;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import br.com.erudio.model.Person;
18 | import br.com.erudio.services.PersonServices;
19 |
20 | @RestController
21 | @RequestMapping("/person")
22 | public class PersonController {
23 |
24 | @Autowired
25 | private PersonServices service;
26 |
27 | @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
28 | public List findAll() {
29 | return service.findAll();
30 | }
31 |
32 | @GetMapping(value = "/{id}",
33 | produces = MediaType.APPLICATION_JSON_VALUE)
34 | public ResponseEntity findById(@PathVariable(value = "id") Long id) {
35 | try {
36 | return ResponseEntity.ok(service.findById(id));
37 | } catch (Exception e) {
38 | return ResponseEntity.notFound().build();
39 | }
40 | }
41 |
42 | @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
43 | produces = MediaType.APPLICATION_JSON_VALUE)
44 | public Person create(@RequestBody Person person) {
45 | return service.create(person);
46 | }
47 |
48 | @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
49 | produces = MediaType.APPLICATION_JSON_VALUE)
50 | public ResponseEntity update(@RequestBody Person person) {
51 | try {
52 | return ResponseEntity.ok(service.update(person));
53 | } catch (Exception e) {
54 | return ResponseEntity.notFound().build();
55 | }
56 | }
57 |
58 | @DeleteMapping(value = "/{id}")
59 | public ResponseEntity> delete(@PathVariable(value = "id") Long id) {
60 | service.delete(id);
61 | return ResponseEntity.noContent().build();
62 | }
63 | }
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ExceptionResponse.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import java.io.Serializable;
4 | import java.util.Date;
5 |
6 | public class ExceptionResponse implements Serializable {
7 |
8 | private static final long serialVersionUID = 1L;
9 |
10 | private Date timestamp;
11 | private String message;
12 | private String details;
13 |
14 | public ExceptionResponse(Date timestamp, String message, String details) {
15 | this.timestamp = timestamp;
16 | this.message = message;
17 | this.details = details;
18 | }
19 |
20 | public Date getTimestamp() {
21 | return timestamp;
22 | }
23 |
24 | public String getMessage() {
25 | return message;
26 | }
27 |
28 | public String getDetails() {
29 | return details;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ResourceNotFoundException.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.bind.annotation.ResponseStatus;
5 |
6 | @ResponseStatus(HttpStatus.NOT_FOUND)
7 | public class ResourceNotFoundException extends RuntimeException{
8 |
9 | private static final long serialVersionUID = 1L;
10 |
11 | public ResourceNotFoundException(String ex) {
12 | super(ex);
13 | }
14 | }
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/handler/CustomizedResponseEntityExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions.handler;
2 |
3 | import java.util.Date;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.bind.annotation.RestController;
10 | import org.springframework.web.context.request.WebRequest;
11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
12 |
13 | import br.com.erudio.exceptions.ExceptionResponse;
14 | import br.com.erudio.exceptions.ResourceNotFoundException;
15 |
16 | @ControllerAdvice
17 | @RestController
18 | public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
19 |
20 | @ExceptionHandler(Exception.class)
21 | public final ResponseEntity handleAllExceptions(
22 | Exception ex, WebRequest request) {
23 |
24 | ExceptionResponse exceptionResponse = new ExceptionResponse(
25 | new Date(),
26 | ex.getMessage(),
27 | request.getDescription(false));
28 |
29 | return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
30 | }
31 |
32 | @ExceptionHandler(ResourceNotFoundException.class)
33 | public final ResponseEntity handleNotFoundExceptions(
34 | Exception ex, WebRequest request) {
35 |
36 | ExceptionResponse exceptionResponse = new ExceptionResponse(
37 | new Date(),
38 | ex.getMessage(),
39 | request.getDescription(false));
40 |
41 | return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/repositories/PersonRepository.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.repositories;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.data.jpa.repository.Query;
7 | import org.springframework.data.repository.query.Param;
8 |
9 | import br.com.erudio.model.Person;
10 |
11 | public interface PersonRepository extends JpaRepository {
12 |
13 | Optional findByEmail(String email);
14 |
15 | // Define custom query using JPQL with index parameters
16 | @Query("select p from Person p where p.firstName =?1 and p.lastName =?2")
17 | Person findByJPQL(String firstName, String lastName);
18 |
19 | // Define custom query using JPQL with named parameters
20 | @Query("select p from Person p where p.firstName =:firstName and p.lastName =:lastName")
21 | Person findByJPQLNamedParameters(
22 | @Param("firstName") String firstName,
23 | @Param("lastName") String lastName);
24 |
25 | // Define custom query using Native SQL with index parameters
26 | @Query(value = "select * from person p where p.first_name =?1 and p.last_name =?2", nativeQuery = true)
27 | Person findByNativeSQL(String firstName, String lastName);
28 |
29 | // Define custom query using Native SQL with named parameters
30 | @Query(value = "select * from person p where p.first_name =:firstName and p.last_name =:lastName", nativeQuery = true)
31 | Person findByNativeSQLwithNamedParameters(
32 | @Param("firstName") String firstName,
33 | @Param("lastName") String lastName);
34 | }
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/services/PersonServices.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.services;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 | import java.util.logging.Logger;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.stereotype.Service;
9 |
10 | import br.com.erudio.exceptions.ResourceNotFoundException;
11 | import br.com.erudio.model.Person;
12 | import br.com.erudio.repositories.PersonRepository;
13 |
14 | @Service
15 | public class PersonServices {
16 |
17 | private Logger logger = Logger.getLogger(PersonServices.class.getName());
18 |
19 | @Autowired
20 | PersonRepository repository;
21 |
22 | public List findAll() {
23 |
24 | logger.info("Finding all people!");
25 |
26 | return repository.findAll();
27 | }
28 |
29 | public Person findById(Long id) {
30 |
31 | logger.info("Finding one person!");
32 |
33 | return repository.findById(id)
34 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
35 | }
36 |
37 | public Person create(Person person) {
38 |
39 | logger.info("Creating one person!");
40 |
41 | Optional savedPerson = repository.findByEmail(person.getEmail());
42 | if(savedPerson.isPresent()) {
43 | throw new ResourceNotFoundException(
44 | "Person already exist with given e-Mail: " + person.getEmail());
45 | }
46 | return repository.save(person);
47 | }
48 |
49 | public Person update(Person person) {
50 |
51 | logger.info("Updating one person!");
52 |
53 | var entity = repository.findById(person.getId())
54 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
55 |
56 | entity.setFirstName(person.getFirstName());
57 | entity.setLastName(person.getLastName());
58 | entity.setAddress(person.getAddress());
59 | entity.setGender(person.getGender());
60 |
61 | return repository.save(person);
62 | }
63 |
64 | public void delete(Long id) {
65 |
66 | logger.info("Deleting one person!");
67 |
68 | var entity = repository.findById(id)
69 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
70 | repository.delete(entity);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | datasource:
3 | driver-class-name: com.mysql.cj.jdbc.Driver
4 | url: jdbc:mysql://localhost:3306/rest_with_spring_boot_erudio?useTimezone=true&serverTimezone=UTC
5 | username: root
6 | password: admin123
7 | jpa:
8 | hibernate:
9 | ddl-auto: update
10 | properties:
11 | hibernate:
12 | dialect: org.hibernate.dialect.MySQL8Dialect
13 | show-sql: false
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/src/test/java/br/com/erudio/StartupTests.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class StartupTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S12_TestingControllers/rest-with-spring-boot-and-java-erudio/src/test/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | datasource:
3 | url: jdbc:h2:~/testdb;DB_CLOSE_ON_EXIT=FALSE
4 | username: sa
5 | password:
6 | driver-class-name: org.h2.Driver
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.0.5
9 |
10 |
11 | br.com.erudio
12 | rest-with-spring-boot-and-java-erudio
13 | 0.0.1-SNAPSHOT
14 | rest-with-spring-boot-and-java-erudio
15 | Demo project for Spring Boot
16 |
17 | 19
18 | 2.1.0
19 | 1.18.0
20 |
21 |
22 |
23 | org.springframework.boot
24 | spring-boot-starter-web
25 |
26 |
27 | org.springframework.boot
28 | spring-boot-starter-data-jpa
29 |
30 |
31 | org.springframework.boot
32 | spring-boot-starter-validation
33 |
34 |
35 |
36 | com.mysql
37 | mysql-connector-j
38 | runtime
39 |
40 |
41 |
42 | org.springdoc
43 | springdoc-openapi-starter-webmvc-ui
44 | ${springdoc.version}
45 |
46 |
47 | io.rest-assured
48 | rest-assured
49 | test
50 |
51 |
52 |
53 | org.testcontainers
54 | mysql
55 | ${testcontainers.version}
56 | test
57 |
58 |
59 |
60 | org.springframework.boot
61 | spring-boot-starter-test
62 | test
63 |
64 |
65 |
66 | org.springframework.boot
67 | spring-boot-devtools
68 | runtime
69 | true
70 |
71 |
72 |
73 |
74 |
75 |
76 | org.springframework.boot
77 | spring-boot-maven-plugin
78 |
79 |
80 |
81 |
82 |
83 |
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/Startup.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Startup {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Startup.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/config/OpenAPIConfig.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | import io.swagger.v3.oas.models.OpenAPI;
7 | import io.swagger.v3.oas.models.info.Info;
8 | import io.swagger.v3.oas.models.info.License;
9 |
10 | @Configuration
11 | public class OpenAPIConfig {
12 |
13 | @Bean
14 | OpenAPI customOpenAPI() {
15 | return new OpenAPI()
16 | .info(new Info()
17 | .title("Hello Swagger OpenAPI")
18 | .version("v1")
19 | .description("Some description about your API.")
20 | .termsOfService("https://pub.erudio.com.br/meus-cursos")
21 | .license(
22 | new License()
23 | .name("Apache 2.0")
24 | .url("https://pub.erudio.com.br/meus-cursos")));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/controllers/PersonController.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.controllers;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.MediaType;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.DeleteMapping;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PostMapping;
12 | import org.springframework.web.bind.annotation.PutMapping;
13 | import org.springframework.web.bind.annotation.RequestBody;
14 | import org.springframework.web.bind.annotation.RequestMapping;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import br.com.erudio.model.Person;
18 | import br.com.erudio.services.PersonServices;
19 |
20 | @RestController
21 | @RequestMapping("/person")
22 | public class PersonController {
23 |
24 | @Autowired
25 | private PersonServices service;
26 |
27 | @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
28 | public List findAll() {
29 | return service.findAll();
30 | }
31 |
32 | @GetMapping(value = "/{id}",
33 | produces = MediaType.APPLICATION_JSON_VALUE)
34 | public ResponseEntity findById(@PathVariable(value = "id") Long id) {
35 | try {
36 | return ResponseEntity.ok(service.findById(id));
37 | } catch (Exception e) {
38 | return ResponseEntity.notFound().build();
39 | }
40 | }
41 |
42 | @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
43 | produces = MediaType.APPLICATION_JSON_VALUE)
44 | public Person create(@RequestBody Person person) {
45 | return service.create(person);
46 | }
47 |
48 | @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
49 | produces = MediaType.APPLICATION_JSON_VALUE)
50 | public ResponseEntity update(@RequestBody Person person) {
51 | try {
52 | return ResponseEntity.ok(service.update(person));
53 | } catch (Exception e) {
54 | return ResponseEntity.notFound().build();
55 | }
56 | }
57 |
58 | @DeleteMapping(value = "/{id}")
59 | public ResponseEntity> delete(@PathVariable(value = "id") Long id) {
60 | service.delete(id);
61 | return ResponseEntity.noContent().build();
62 | }
63 | }
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ExceptionResponse.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import java.io.Serializable;
4 | import java.util.Date;
5 |
6 | public class ExceptionResponse implements Serializable {
7 |
8 | private static final long serialVersionUID = 1L;
9 |
10 | private Date timestamp;
11 | private String message;
12 | private String details;
13 |
14 | public ExceptionResponse(Date timestamp, String message, String details) {
15 | this.timestamp = timestamp;
16 | this.message = message;
17 | this.details = details;
18 | }
19 |
20 | public Date getTimestamp() {
21 | return timestamp;
22 | }
23 |
24 | public String getMessage() {
25 | return message;
26 | }
27 |
28 | public String getDetails() {
29 | return details;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/ResourceNotFoundException.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.bind.annotation.ResponseStatus;
5 |
6 | @ResponseStatus(HttpStatus.NOT_FOUND)
7 | public class ResourceNotFoundException extends RuntimeException{
8 |
9 | private static final long serialVersionUID = 1L;
10 |
11 | public ResourceNotFoundException(String ex) {
12 | super(ex);
13 | }
14 | }
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/exceptions/handler/CustomizedResponseEntityExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.exceptions.handler;
2 |
3 | import java.util.Date;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.bind.annotation.RestController;
10 | import org.springframework.web.context.request.WebRequest;
11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
12 |
13 | import br.com.erudio.exceptions.ExceptionResponse;
14 | import br.com.erudio.exceptions.ResourceNotFoundException;
15 |
16 | @ControllerAdvice
17 | @RestController
18 | public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
19 |
20 | @ExceptionHandler(Exception.class)
21 | public final ResponseEntity handleAllExceptions(
22 | Exception ex, WebRequest request) {
23 |
24 | ExceptionResponse exceptionResponse = new ExceptionResponse(
25 | new Date(),
26 | ex.getMessage(),
27 | request.getDescription(false));
28 |
29 | return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
30 | }
31 |
32 | @ExceptionHandler(ResourceNotFoundException.class)
33 | public final ResponseEntity handleNotFoundExceptions(
34 | Exception ex, WebRequest request) {
35 |
36 | ExceptionResponse exceptionResponse = new ExceptionResponse(
37 | new Date(),
38 | ex.getMessage(),
39 | request.getDescription(false));
40 |
41 | return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/repositories/PersonRepository.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.repositories;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.data.jpa.repository.Query;
7 | import org.springframework.data.repository.query.Param;
8 |
9 | import br.com.erudio.model.Person;
10 |
11 | public interface PersonRepository extends JpaRepository {
12 |
13 | Optional findByEmail(String email);
14 |
15 | // Define custom query using JPQL with index parameters
16 | @Query("select p from Person p where p.firstName =?1 and p.lastName =?2")
17 | Person findByJPQL(String firstName, String lastName);
18 |
19 | // Define custom query using JPQL with named parameters
20 | @Query("select p from Person p where p.firstName =:firstName and p.lastName =:lastName")
21 | Person findByJPQLNamedParameters(
22 | @Param("firstName") String firstName,
23 | @Param("lastName") String lastName);
24 |
25 | // Define custom query using Native SQL with index parameters
26 | @Query(value = "select * from person p where p.first_name =?1 and p.last_name =?2", nativeQuery = true)
27 | Person findByNativeSQL(String firstName, String lastName);
28 |
29 | // Define custom query using Native SQL with named parameters
30 | @Query(value = "select * from person p where p.first_name =:firstName and p.last_name =:lastName", nativeQuery = true)
31 | Person findByNativeSQLwithNamedParameters(
32 | @Param("firstName") String firstName,
33 | @Param("lastName") String lastName);
34 | }
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/main/java/br/com/erudio/services/PersonServices.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.services;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 | import java.util.logging.Logger;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.stereotype.Service;
9 |
10 | import br.com.erudio.exceptions.ResourceNotFoundException;
11 | import br.com.erudio.model.Person;
12 | import br.com.erudio.repositories.PersonRepository;
13 |
14 | @Service
15 | public class PersonServices {
16 |
17 | private Logger logger = Logger.getLogger(PersonServices.class.getName());
18 |
19 | @Autowired
20 | PersonRepository repository;
21 |
22 | public List findAll() {
23 |
24 | logger.info("Finding all people!");
25 |
26 | return repository.findAll();
27 | }
28 |
29 | public Person findById(Long id) {
30 |
31 | logger.info("Finding one person!");
32 |
33 | return repository.findById(id)
34 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
35 | }
36 |
37 | public Person create(Person person) {
38 |
39 | logger.info("Creating one person!");
40 |
41 | Optional savedPerson = repository.findByEmail(person.getEmail());
42 | if(savedPerson.isPresent()) {
43 | throw new ResourceNotFoundException(
44 | "Person already exist with given e-Mail: " + person.getEmail());
45 | }
46 | return repository.save(person);
47 | }
48 |
49 | public Person update(Person person) {
50 |
51 | logger.info("Updating one person!");
52 |
53 | var entity = repository.findById(person.getId())
54 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
55 |
56 | entity.setFirstName(person.getFirstName());
57 | entity.setLastName(person.getLastName());
58 | entity.setAddress(person.getAddress());
59 | entity.setGender(person.getGender());
60 |
61 | return repository.save(person);
62 | }
63 |
64 | public void delete(Long id) {
65 |
66 | logger.info("Deleting one person!");
67 |
68 | var entity = repository.findById(id)
69 | .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID!"));
70 | repository.delete(entity);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | datasource:
3 | driver-class-name: com.mysql.cj.jdbc.Driver
4 | url: jdbc:mysql://localhost:3306/rest_with_spring_boot_erudio?useTimezone=true&serverTimezone=UTC
5 | username: root
6 | password: admin123
7 | jpa:
8 | hibernate:
9 | ddl-auto: update
10 | properties:
11 | hibernate:
12 | dialect: org.hibernate.dialect.MySQL8Dialect
13 | show-sql: false
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/test/java/br/com/erudio/config/TestConfigs.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.config;
2 |
3 | public class TestConfigs {
4 |
5 | public static final int SERVER_PORT = 8888;
6 | public static final String CONTENT_TYPE_JSON = "application/json";
7 | }
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/test/java/br/com/erudio/integrationtests/swagger/SwaggerIntegrationTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.integrationtests.swagger;
2 |
3 | import static io.restassured.RestAssured.given;
4 | import static org.junit.Assert.assertTrue;
5 |
6 | import org.junit.jupiter.api.DisplayName;
7 | import org.junit.jupiter.api.Test;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 |
10 | import br.com.erudio.config.TestConfigs;
11 | import br.com.erudio.integrationtests.testcontainers.AbstractIntegrationTest;
12 |
13 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
14 | class SwaggerIntegrationTest extends AbstractIntegrationTest {
15 |
16 | @Test
17 | @DisplayName("JUnit test for Should Display Swagger UI Page")
18 | void testShouldDisplaySwaggerUiPage() {
19 | var content = given()
20 | .basePath("/swagger-ui/index.html")
21 | .port(TestConfigs.SERVER_PORT)
22 | .when()
23 | .get()
24 | .then()
25 | .statusCode(200)
26 | .extract()
27 | .body()
28 | .asString();
29 | assertTrue(content.contains("Swagger UI"));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/test/java/br/com/erudio/integrationtests/testcontainers/AbstractIntegrationTest.java:
--------------------------------------------------------------------------------
1 | package br.com.erudio.integrationtests.testcontainers;
2 |
3 | import java.util.Map;
4 | import java.util.stream.Stream;
5 |
6 | import org.springframework.context.ApplicationContextInitializer;
7 | import org.springframework.context.ConfigurableApplicationContext;
8 | import org.springframework.core.env.ConfigurableEnvironment;
9 | import org.springframework.core.env.MapPropertySource;
10 | import org.springframework.test.context.ContextConfiguration;
11 | import org.testcontainers.containers.MySQLContainer;
12 | import org.testcontainers.lifecycle.Startables;
13 |
14 | @ContextConfiguration(initializers = AbstractIntegrationTest.Initializer.class)
15 | public class AbstractIntegrationTest {
16 |
17 | static class Initializer implements ApplicationContextInitializer {
18 |
19 | static MySQLContainer> mysql = new MySQLContainer<>("mysql:8.0.28");
20 |
21 | private static void startContainers() {
22 | Startables.deepStart(Stream.of(mysql)).join();
23 | }
24 |
25 | private static Map createConnectionConfiguration(){
26 | return Map.of(
27 | "spring.datasource.url", mysql.getJdbcUrl(),
28 | "spring.datasource.username", mysql.getUsername(),
29 | "spring.datasource.password", mysql.getPassword());
30 | }
31 |
32 | @Override
33 | @SuppressWarnings({ "rawtypes", "unchecked" })
34 | public void initialize(ConfigurableApplicationContext applicationContext) {
35 | startContainers();
36 | ConfigurableEnvironment environment = applicationContext.getEnvironment();
37 | MapPropertySource testcontainers =
38 | new MapPropertySource(
39 | "testcontainers",
40 | (Map) createConnectionConfiguration());
41 |
42 | environment.getPropertySources().addFirst(testcontainers);
43 | }
44 |
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/S13_IntegrationTests/rest-with-spring-boot-and-java-erudio/src/test/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8888
3 | spring:
4 | datasource:
5 | driver-class-name: com.mysql.cj.jdbc.Driver
6 | jpa:
7 | hibernate:
8 | ddl-auto: update
9 | properties:
10 | hibernate:
11 | dialect: org.hibernate.dialect.MySQL8Dialect
12 | show-sql: false
--------------------------------------------------------------------------------