From 9e1f3c0899f023dc2d2bf4c480ba555b0d234e71 Mon Sep 17 00:00:00 2001 From: YuCheng Hu Date: Mon, 22 Nov 2021 13:31:26 -0500 Subject: [PATCH] Add Junit5 test base --- testing/junit-5-basics/README.md | 11 ++ testing/junit-5-basics/pom.xml | 129 ++++++++++++++++++ .../failure_vs_error/SimpleCalculator.java | 15 ++ .../baeldung/junit/tags/example/Employee.java | 44 ++++++ .../junit/tags/example/EmployeeDAO.java | 58 ++++++++ .../junit/tags/example/EmployeeRowMapper.java | 21 +++ .../junit/tags/example/SpringJdbcConfig.java | 19 +++ .../java/com/baeldung/junit5/Greetings.java | 9 ++ .../com/baeldung/junit5/bean/NumbersBean.java | 22 +++ .../src/main/resources/jdbc/schema.sql | 7 + .../main/resources/jdbc/springJdbc-config.xml | 19 +++ .../src/main/resources/jdbc/test-data.sql | 7 + .../java/com/baeldung/ExceptionUnitTest.java | 40 ++++++ .../test/java/com/baeldung/FirstUnitTest.java | 33 +++++ .../java/com/baeldung/GreetingsUnitTest.java | 19 +++ .../baeldung/JUnit5NewFeaturesUnitTest.java | 50 +++++++ .../src/test/java/com/baeldung/LiveTest.java | 39 ++++++ .../ExceptionAssertionUnitTest.java | 32 +++++ .../junit4/ExceptionAssertionUnitTest.java | 24 ++++ .../EmployeeDAOCategoryIntegrationTest.java | 66 +++++++++ .../categories/EmployeeDAOUnitTestSuite.java | 12 ++ .../baeldung/categories/IntegrationTest.java | 4 + .../com/baeldung/categories/UnitTest.java | 4 + .../example/EmployeeDAOIntegrationTest.java | 45 ++++++ .../baeldung/example/EmployeeUnitTest.java | 40 ++++++ .../SharedTemporaryDirectoryUnitTest.java | 49 +++++++ .../tempdir/TemporaryDirectoryUnitTest.java | 48 +++++++ .../SimpleCalculatorUnitTest.java | 39 ++++++ .../junit5/bean/test/NumbersBeanUnitTest.java | 43 ++++++ .../spring/GreetingsSpringUnitTest.java | 21 +++ .../spring/SpringTestConfiguration.java | 8 ++ .../junit4/AnnotationTestExampleUnitTest.java | 23 ++++ .../junit4/AssertionsExampleUnitTest.java | 28 ++++ .../BeforeAndAfterAnnotationsUnitTest.java | 51 +++++++ ...ClassAndAfterClassAnnotationsUnitTest.java | 35 +++++ .../migration/junit4/RuleExampleUnitTest.java | 18 +++ .../junit4/categories/Annotations.java | 5 + .../junit4/categories/JUnit4UnitTest.java | 5 + .../junit4/rules/TraceUnitTestRule.java | 35 +++++ .../junit5/AnnotationTestExampleUnitTest.java | 28 ++++ .../junit5/AssertionsExampleUnitTest.java | 40 ++++++ .../migration/junit5/AssumptionUnitTest.java | 29 ++++ ...foreAllAndAfterAllAnnotationsUnitTest.java | 35 +++++ ...reEachAndAfterEachAnnotationsUnitTest.java | 51 +++++++ .../migration/junit5/RuleExampleUnitTest.java | 19 +++ .../junit5/extensions/TraceUnitExtension.java | 19 +++ .../ReadResourceDirectoryUnitTest.java | 45 ++++++ .../java/com/baeldung/suites/AllUnitTest.java | 12 ++ .../tags/EmployeeDAOIntegrationTest.java | 69 ++++++++++ .../baeldung/tags/EmployeeDAOTestSuite.java | 12 ++ .../src/test/resources/example_resource.txt | 0 51 files changed, 1536 insertions(+) create mode 100644 testing/junit-5-basics/README.md create mode 100644 testing/junit-5-basics/pom.xml create mode 100644 testing/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java create mode 100644 testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/Employee.java create mode 100644 testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeDAO.java create mode 100644 testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeRowMapper.java create mode 100644 testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/SpringJdbcConfig.java create mode 100644 testing/junit-5-basics/src/main/java/com/baeldung/junit5/Greetings.java create mode 100644 testing/junit-5-basics/src/main/java/com/baeldung/junit5/bean/NumbersBean.java create mode 100644 testing/junit-5-basics/src/main/resources/jdbc/schema.sql create mode 100644 testing/junit-5-basics/src/main/resources/jdbc/springJdbc-config.xml create mode 100644 testing/junit-5-basics/src/main/resources/jdbc/test-data.sql create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/ExceptionUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/FirstUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/LiveTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/assertexception/ExceptionAssertionUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/assertexception/migration/junit4/ExceptionAssertionUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOCategoryIntegrationTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOUnitTestSuite.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/categories/IntegrationTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/categories/UnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/example/EmployeeDAOIntegrationTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/example/EmployeeUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/SharedTemporaryDirectoryUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/TemporaryDirectoryUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOIntegrationTest.java create mode 100644 testing/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java create mode 100644 testing/junit-5-basics/src/test/resources/example_resource.txt diff --git a/testing/junit-5-basics/README.md b/testing/junit-5-basics/README.md new file mode 100644 index 0000000000..31eb75a792 --- /dev/null +++ b/testing/junit-5-basics/README.md @@ -0,0 +1,11 @@ +### Relevant Articles: +- [A Guide to JUnit 5](http://www.baeldung.com/junit-5) +- [JUnit5 @RunWith](http://www.baeldung.com/junit-5-runwith) +- [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path) +- [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junit-filtering-tests) +- [JUnit 5 Temporary Directory Support](https://www.baeldung.com/junit-5-temporary-directory) +- [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) +- [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) +- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) +- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) +- [The Difference Between Failure and Error in JUnit](https://www.baeldung.com/junit-failure-vs-error) diff --git a/testing/junit-5-basics/pom.xml b/testing/junit-5-basics/pom.xml new file mode 100644 index 0000000000..d905d55df1 --- /dev/null +++ b/testing/junit-5-basics/pom.xml @@ -0,0 +1,129 @@ + + + 4.0.0 + junit-5-basics + 1.0-SNAPSHOT + junit-5-basics + Intro to JUnit 5 + + + com.ossez + testing + 0.0.2-SNAPSHOT + ../ + + + + + org.junit.platform + junit-platform-runner + ${junit-platform.version} + test + + + org.junit.jupiter + junit-jupiter-migrationsupport + ${junit-jupiter.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.springframework + spring-test + ${spring.version} + test + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-orm + ${spring.version} + + + + + + + src/test/resources + true + + + src/main/resources + true + + + + + + + filtering + + false + + + + + org.apache.maven.surefire + maven-surefire-plugin + + + **/*IntegrationTest.java + + + + + + + + category + + false + + + + + org.apache.maven.surefire + maven-surefire-plugin + + com.baeldung.categories.UnitTest + com.baeldung.categories.IntegrationTest + + + + + + + tags + + false + + + + + org.apache.maven.surefire + maven-surefire-plugin + + UnitTest + IntegrationTest + + + + + + + + + 5.0.6.RELEASE + + + \ No newline at end of file diff --git a/testing/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java b/testing/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java new file mode 100644 index 0000000000..d018aa939f --- /dev/null +++ b/testing/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java @@ -0,0 +1,15 @@ +package com.baeldung.failure_vs_error; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +public class SimpleCalculator { + + public static double divideNumbers(double dividend, double divisor) { + if (divisor == 0) { + throw new ArithmeticException("Division by zero!"); + } + return dividend / divisor; + } +} diff --git a/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/Employee.java b/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/Employee.java new file mode 100644 index 0000000000..66f41ee885 --- /dev/null +++ b/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/Employee.java @@ -0,0 +1,44 @@ +package com.baeldung.junit.tags.example; + +public class Employee { + private int id; + + private String firstName; + + private String lastName; + + private String address; + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + public String getAddress() { + return address; + } + + public void setAddress(final String address) { + this.address = address; + } + +} diff --git a/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeDAO.java b/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeDAO.java new file mode 100644 index 0000000000..2e9016018e --- /dev/null +++ b/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeDAO.java @@ -0,0 +1,58 @@ +package com.baeldung.junit.tags.example; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import org.springframework.jdbc.core.simple.SimpleJdbcInsert; +import org.springframework.stereotype.Repository; + +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Repository +public class EmployeeDAO { + + private JdbcTemplate jdbcTemplate; + + private NamedParameterJdbcTemplate namedParameterJdbcTemplate; + + private SimpleJdbcInsert simpleJdbcInsert; + + @Autowired + public void setDataSource(final DataSource dataSource) { + jdbcTemplate = new JdbcTemplate(dataSource); + + namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); + simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("EMPLOYEE"); + + } + + public int getCountOfEmployees() { + return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class); + } + + public List getAllEmployees() { + return jdbcTemplate.query("SELECT * FROM EMPLOYEE", new EmployeeRowMapper()); + } + + public int addEmplyee(final int id) { + return jdbcTemplate.update("INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)", id, "Bill", "Gates", "USA"); + } + + public int addEmplyeeUsingSimpelJdbcInsert(final Employee emp) { + final Map parameters = new HashMap(); + parameters.put("ID", emp.getId()); + parameters.put("FIRST_NAME", emp.getFirstName()); + parameters.put("LAST_NAME", emp.getLastName()); + parameters.put("ADDRESS", emp.getAddress()); + + return simpleJdbcInsert.execute(parameters); + } + + // for testing + public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } +} diff --git a/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeRowMapper.java b/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeRowMapper.java new file mode 100644 index 0000000000..f480aac9a2 --- /dev/null +++ b/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/EmployeeRowMapper.java @@ -0,0 +1,21 @@ +package com.baeldung.junit.tags.example; + +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class EmployeeRowMapper implements RowMapper { + + @Override + public Employee mapRow(final ResultSet rs, final int rowNum) throws SQLException { + final Employee employee = new Employee(); + + employee.setId(rs.getInt("ID")); + employee.setFirstName(rs.getString("FIRST_NAME")); + employee.setLastName(rs.getString("LAST_NAME")); + employee.setAddress(rs.getString("ADDRESS")); + + return employee; + } +} diff --git a/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/SpringJdbcConfig.java b/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/SpringJdbcConfig.java new file mode 100644 index 0000000000..dc82409df9 --- /dev/null +++ b/testing/junit-5-basics/src/main/java/com/baeldung/junit/tags/example/SpringJdbcConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.junit.tags.example; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +import javax.sql.DataSource; + +@Configuration +@ComponentScan("com.baeldung.junit.tags.example") +public class SpringJdbcConfig { + + @Bean + public DataSource dataSource() { + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).addScript("classpath:jdbc/schema.sql").addScript("classpath:jdbc/test-data.sql").build(); + } +} \ No newline at end of file diff --git a/testing/junit-5-basics/src/main/java/com/baeldung/junit5/Greetings.java b/testing/junit-5-basics/src/main/java/com/baeldung/junit5/Greetings.java new file mode 100644 index 0000000000..f43269f646 --- /dev/null +++ b/testing/junit-5-basics/src/main/java/com/baeldung/junit5/Greetings.java @@ -0,0 +1,9 @@ +package com.baeldung.junit5; + +public class Greetings { + + public static String sayHello() { + return "Hello"; + } + +} diff --git a/testing/junit-5-basics/src/main/java/com/baeldung/junit5/bean/NumbersBean.java b/testing/junit-5-basics/src/main/java/com/baeldung/junit5/bean/NumbersBean.java new file mode 100644 index 0000000000..48730fd844 --- /dev/null +++ b/testing/junit-5-basics/src/main/java/com/baeldung/junit5/bean/NumbersBean.java @@ -0,0 +1,22 @@ +package com.baeldung.junit5.bean; + +/** + * Bean that contains utility methods to work with numbers. + * + * @author Donato Rimenti + * + */ +public class NumbersBean { + + /** + * Returns true if a number is even, false otherwise. + * + * @param number + * the number to check + * @return true if the argument is even, false otherwise + */ + public boolean isNumberEven(int number) { + return number % 2 == 0; + } + +} diff --git a/testing/junit-5-basics/src/main/resources/jdbc/schema.sql b/testing/junit-5-basics/src/main/resources/jdbc/schema.sql new file mode 100644 index 0000000000..c86d35cdae --- /dev/null +++ b/testing/junit-5-basics/src/main/resources/jdbc/schema.sql @@ -0,0 +1,7 @@ +CREATE TABLE EMPLOYEE +( + ID int NOT NULL PRIMARY KEY, + FIRST_NAME varchar(255), + LAST_NAME varchar(255), + ADDRESS varchar(255), +); \ No newline at end of file diff --git a/testing/junit-5-basics/src/main/resources/jdbc/springJdbc-config.xml b/testing/junit-5-basics/src/main/resources/jdbc/springJdbc-config.xml new file mode 100644 index 0000000000..5fd2699b41 --- /dev/null +++ b/testing/junit-5-basics/src/main/resources/jdbc/springJdbc-config.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testing/junit-5-basics/src/main/resources/jdbc/test-data.sql b/testing/junit-5-basics/src/main/resources/jdbc/test-data.sql new file mode 100644 index 0000000000..b9ef8fec25 --- /dev/null +++ b/testing/junit-5-basics/src/main/resources/jdbc/test-data.sql @@ -0,0 +1,7 @@ +INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada'); + +INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA'); + +INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland'); + +INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA'); \ No newline at end of file diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/ExceptionUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/ExceptionUnitTest.java new file mode 100644 index 0000000000..440c3e40ab --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/ExceptionUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.ConcurrentModificationException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +public class ExceptionUnitTest { + + @Test + void shouldThrowException() { + Throwable exception = assertThrows(UnsupportedOperationException.class, () -> { + throw new UnsupportedOperationException("Not supported"); + }); + assertEquals(exception.getMessage(), "Not supported"); + } + + @Test + void assertThrowsException() { + String str = null; + assertThrows(IllegalArgumentException.class, () -> { + Integer.valueOf(str); + }); + } + + @Test + public void whenModifyMapDuringIteration_thenThrowExecption() { + Map hashmap = new HashMap<>(); + hashmap.put(1, "One"); + hashmap.put(2, "Two"); + + Executable executable = () -> hashmap.forEach((key, value) -> hashmap.remove(1)); + assertThrows(ConcurrentModificationException.class, executable); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/FirstUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/FirstUnitTest.java new file mode 100644 index 0000000000..c47a70e52f --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/FirstUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +class FirstUnitTest { + + @Test + void lambdaExpressions() { + List numbers = Arrays.asList(1, 2, 3); + assertTrue(numbers.stream() + .mapToInt(i -> i) + .sum() > 5, "Sum should be greater than 5"); + } + + @Disabled("test to show MultipleFailuresError") + @Test + void groupAssertions() { + int[] numbers = { 0, 1, 2, 3, 4 }; + assertAll("numbers", () -> assertEquals(numbers[0], 1), () -> assertEquals(numbers[3], 3), () -> assertEquals(numbers[4], 1)); + } + + @Test + @Disabled + void disabledTest() { + assertTrue(false); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java new file mode 100644 index 0000000000..a07162ceed --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.baeldung.junit5.Greetings; + +@RunWith(JUnitPlatform.class) +public class GreetingsUnitTest { + + @Test + void whenCallingSayHello_thenReturnHello() { + assertTrue("Hello".equals(Greetings.sayHello())); + } + +} \ No newline at end of file diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java new file mode 100644 index 0000000000..311c62f425 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung; + +import java.util.logging.Logger; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +//@RunWith(JUnitPlatform.class) +public class JUnit5NewFeaturesUnitTest { + + private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName()); + + @BeforeAll + static void setup() { + log.info("@BeforeAll - executes once before all test methods in this class"); + } + + @BeforeEach + void init() { + log.info("@BeforeEach - executes before each test method in this class"); + } + + @DisplayName("Single test successful") + @Test + void testSingleSuccessTest() { + log.info("Success"); + + } + + @Test + @Disabled("Not implemented yet.") + void testShowSomething() { + } + + @AfterEach + void tearDown() { + log.info("@AfterEach - executed after each test method."); + } + + @AfterAll + static void done() { + log.info("@AfterAll - executed after all test methods."); + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/LiveTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/LiveTest.java new file mode 100644 index 0000000000..c23eeb5afa --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/LiveTest.java @@ -0,0 +1,39 @@ +package com.baeldung; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; + +public class LiveTest { + + private List in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No")); + private List out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie")); + + @TestFactory + public Stream translateDynamicTestsFromStream() { + + return in.stream() + .map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> { + int id = in.indexOf(word); + assertEquals(out.get(id), translate(word)); + })); + } + + private String translate(String word) { + if ("Hello".equalsIgnoreCase(word)) { + return "Cześć"; + } else if ("Yes".equalsIgnoreCase(word)) { + return "Tak"; + } else if ("No".equalsIgnoreCase(word)) { + return "Nie"; + } + return "Error"; + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/assertexception/ExceptionAssertionUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/assertexception/ExceptionAssertionUnitTest.java new file mode 100644 index 0000000000..ee2f696408 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/assertexception/ExceptionAssertionUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.assertexception; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +public class ExceptionAssertionUnitTest { + @Test + public void whenExceptionThrown_thenAssertionSucceeds() { + Exception exception = assertThrows(NumberFormatException.class, () -> { + Integer.parseInt("1a"); + }); + + String expectedMessage = "For input string"; + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); + } + + @Test + public void whenDerivedExceptionThrown_thenAssertionSucceds() { + Exception exception = assertThrows(RuntimeException.class, () -> { + Integer.parseInt("1a"); + }); + + String expectedMessage = "For input string"; + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); + } +} \ No newline at end of file diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/assertexception/migration/junit4/ExceptionAssertionUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/assertexception/migration/junit4/ExceptionAssertionUnitTest.java new file mode 100644 index 0000000000..62736b0800 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/assertexception/migration/junit4/ExceptionAssertionUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.assertexception.migration.junit4; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class ExceptionAssertionUnitTest { + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @Test(expected = NullPointerException.class) + public void whenExceptionThrown_thenExpectationSatisfied() { + String test = null; + test.length(); + } + + @Test + public void whenExceptionThrown_thenRuleIsApplied() { + exceptionRule.expect(NumberFormatException.class); + exceptionRule.expectMessage("For input string"); + Integer.parseInt("1a"); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOCategoryIntegrationTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOCategoryIntegrationTest.java new file mode 100644 index 0000000000..6aa1652321 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOCategoryIntegrationTest.java @@ -0,0 +1,66 @@ +package com.baeldung.categories; + +import com.baeldung.junit.tags.example.Employee; +import com.baeldung.junit.tags.example.EmployeeDAO; +import com.baeldung.junit.tags.example.SpringJdbcConfig; +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class) +public class EmployeeDAOCategoryIntegrationTest { + + @Autowired + private EmployeeDAO employeeDao; + + @Mock + private JdbcTemplate jdbcTemplate; + private EmployeeDAO employeeDAO; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + employeeDAO = new EmployeeDAO(); + employeeDAO.setJdbcTemplate(jdbcTemplate); + } + + @Test + @Category(IntegrationTest.class) + public void testAddEmployeeUsingSimpelJdbcInsert() { + final Employee emp = new Employee(); + emp.setId(12); + emp.setFirstName("testFirstName"); + emp.setLastName("testLastName"); + emp.setAddress("testAddress"); + + Assert.assertEquals(employeeDao.addEmplyeeUsingSimpelJdbcInsert(emp), 1); + } + + @Test + @Category(UnitTest.class) + public void givenNumberOfEmployeeWhenCountEmployeeThenCountMatch() { + + // given + Mockito.when(jdbcTemplate.queryForObject(Mockito.any(String.class), Mockito.eq(Integer.class))) + .thenReturn(1); + + // when + int countOfEmployees = employeeDAO.getCountOfEmployees(); + + // then + Assert.assertThat(countOfEmployees, CoreMatchers.is(1)); + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOUnitTestSuite.java b/testing/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOUnitTestSuite.java new file mode 100644 index 0000000000..252e7ffe64 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/categories/EmployeeDAOUnitTestSuite.java @@ -0,0 +1,12 @@ +package com.baeldung.categories; + +import org.junit.experimental.categories.Categories; +import org.junit.experimental.categories.Categories.IncludeCategory; +import org.junit.runner.RunWith; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Categories.class) +@IncludeCategory(UnitTest.class) +@SuiteClasses(EmployeeDAOCategoryIntegrationTest.class) +public class EmployeeDAOUnitTestSuite { +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/categories/IntegrationTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/categories/IntegrationTest.java new file mode 100644 index 0000000000..9ced880ffc --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/categories/IntegrationTest.java @@ -0,0 +1,4 @@ +package com.baeldung.categories; + +public interface IntegrationTest { +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/categories/UnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/categories/UnitTest.java new file mode 100644 index 0000000000..3790fc1d91 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/categories/UnitTest.java @@ -0,0 +1,4 @@ +package com.baeldung.categories; + +public interface UnitTest { +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/example/EmployeeDAOIntegrationTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/example/EmployeeDAOIntegrationTest.java new file mode 100644 index 0000000000..2595f2b13c --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/example/EmployeeDAOIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.example; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.junit.tags.example.Employee; +import com.baeldung.junit.tags.example.EmployeeDAO; +import com.baeldung.junit.tags.example.SpringJdbcConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) +public class EmployeeDAOIntegrationTest { + + @Autowired + private EmployeeDAO employeeDao; + + @Test + public void testQueryMethod() { + Assert.assertEquals(employeeDao.getAllEmployees().size(), 4); + } + + @Test + public void testUpdateMethod() { + Assert.assertEquals(employeeDao.addEmplyee(5), 1); + } + + @Test + public void testAddEmployeeUsingSimpelJdbcInsert() { + final Employee emp = new Employee(); + emp.setId(11); + emp.setFirstName("testFirstName"); + emp.setLastName("testLastName"); + emp.setAddress("testAddress"); + + Assert.assertEquals(employeeDao.addEmplyeeUsingSimpelJdbcInsert(emp), 1); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/example/EmployeeUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/example/EmployeeUnitTest.java new file mode 100644 index 0000000000..f706af94ad --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/example/EmployeeUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.example; + +import com.baeldung.junit.tags.example.EmployeeDAO; +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.jdbc.core.JdbcTemplate; + +public class EmployeeUnitTest { + + @Mock + private JdbcTemplate jdbcTemplate; + + private EmployeeDAO employeeDAO; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + employeeDAO = new EmployeeDAO(); + employeeDAO.setJdbcTemplate(jdbcTemplate); + } + + @Test + public void givenNumberOfEmployeeWhenCountEmployeeThenCountMatch() { + + // given + Mockito.when(jdbcTemplate.queryForObject(Mockito.any(String.class), Mockito.eq(Integer.class))) + .thenReturn(1); + + // when + int countOfEmployees = employeeDAO.getCountOfEmployees(); + + // then + Assert.assertThat(countOfEmployees, CoreMatchers.is(1)); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/SharedTemporaryDirectoryUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/SharedTemporaryDirectoryUnitTest.java new file mode 100644 index 0000000000..9483a33143 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/SharedTemporaryDirectoryUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.extensions.tempdir; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertLinesMatch; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.io.TempDir; + +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; + +@TestMethodOrder(OrderAnnotation.class) +class SharedTemporaryDirectoryUnitTest { + + @TempDir + static Path sharedTempDir; + + @Test + @Order(1) + void givenFieldWithSharedTempDirectoryPath_whenWriteToFile_thenContentIsCorrect() throws IOException { + Path numbers = sharedTempDir.resolve("numbers.txt"); + + List lines = Arrays.asList("1", "2", "3"); + Files.write(numbers, lines); + + assertAll( + () -> assertTrue("File should exist", Files.exists(numbers)), + () -> assertLinesMatch(lines, Files.readAllLines(numbers))); + + Files.createTempDirectory("bpb"); + } + + @Test + @Order(2) + void givenAlreadyWrittenToSharedFile_whenCheckContents_thenContentIsCorrect() throws IOException { + Path numbers = sharedTempDir.resolve("numbers.txt"); + + assertLinesMatch(Arrays.asList("1", "2", "3"), Files.readAllLines(numbers)); + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/TemporaryDirectoryUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/TemporaryDirectoryUnitTest.java new file mode 100644 index 0000000000..c6f1a7cd77 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/TemporaryDirectoryUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.extensions.tempdir; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertLinesMatch; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class TemporaryDirectoryUnitTest { + + @Test + void givenTestMethodWithTempDirectoryPath_whenWriteToFile_thenContentIsCorrect(@TempDir Path tempDir) throws IOException { + Path numbers = tempDir.resolve("numbers.txt"); + + List lines = Arrays.asList("1", "2", "3"); + Files.write(numbers, lines); + + assertAll( + () -> assertTrue("File should exist", Files.exists(numbers)), + () -> assertLinesMatch(lines, Files.readAllLines(numbers))); + } + + @TempDir + File anotherTempDir; + + @Test + void givenFieldWithTempDirectoryFile_whenWriteToFile_thenContentIsCorrect() throws IOException { + assertTrue("Should be a directory ", this.anotherTempDir.isDirectory()); + + File letters = new File(anotherTempDir, "letters.txt"); + List lines = Arrays.asList("x", "y", "z"); + + Files.write(letters.toPath(), lines); + + assertAll( + () -> assertTrue("File should exist", Files.exists(letters.toPath())), + () -> assertLinesMatch(lines, Files.readAllLines(letters.toPath()))); + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java new file mode 100644 index 0000000000..1640bd714c --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.failure_vs_error; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +class SimpleCalculatorUnitTest { + + @Test + void whenDivideByValidNumber_thenAssertCorrectResult() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(2, result); + } + + @Test + @Disabled("test is expected to fail, disabled so that CI build still goes through") + void whenDivideNumbers_thenExpectWrongResult() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(15, result); + } + + @Test + @Disabled("test is expected to raise an error, disabled so that CI build still goes through") + void whenDivideByZero_thenThrowsException() { + SimpleCalculator.divideNumbers(10, 0); + } + + @Test + void whenDivideByZero_thenAssertException() { + assertThrows(ArithmeticException.class, () -> SimpleCalculator.divideNumbers(10, 0)); + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java new file mode 100644 index 0000000000..0297d010e8 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.junit5.bean.test; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import com.baeldung.junit5.bean.NumbersBean; + +/** + * Test class for {@link NumbersBean}. + * + * @author Donato Rimenti + * + */ +public class NumbersBeanUnitTest { + + /** + * The bean to test. + */ + private NumbersBean bean = new NumbersBean(); + + /** + * Tests that when an even number is passed to + * {@link NumbersBean#isNumberEven(int)}, true is returned. + */ + @Test + void givenEvenNumber_whenCheckingIsNumberEven_thenTrue() { + boolean result = bean.isNumberEven(8); + + Assertions.assertTrue(result); + } + + /** + * Tests that when an odd number is passed to + * {@link NumbersBean#isNumberEven(int)}, false is returned. + */ + @Test + void givenOddNumber_whenCheckingIsNumberEven_thenFalse() { + boolean result = bean.isNumberEven(3); + + Assertions.assertFalse(result); + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java new file mode 100644 index 0000000000..317a0797ed --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.junit5.spring; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.junit5.Greetings; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { SpringTestConfiguration.class }) +public class GreetingsSpringUnitTest { + + @Test + void whenCallingSayHello_thenReturnHello() { + assertTrue("Hello".equals(Greetings.sayHello())); + } + +} \ No newline at end of file diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java b/testing/junit-5-basics/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java new file mode 100644 index 0000000000..7651b2bd41 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java @@ -0,0 +1,8 @@ +package com.baeldung.junit5.spring; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringTestConfiguration { + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java new file mode 100644 index 0000000000..45671f200d --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.migration.junit4; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import com.baeldung.migration.junit4.categories.Annotations; +import com.baeldung.migration.junit4.categories.JUnit4UnitTest; + +@Category(value = { Annotations.class, JUnit4UnitTest.class }) +public class AnnotationTestExampleUnitTest { + @Test(expected = Exception.class) + public void shouldRaiseAnException() throws Exception { + throw new Exception("This is my expected exception"); + } + + @Test(timeout = 1) + @Ignore + public void shouldFailBecauseTimeout() throws InterruptedException { + Thread.sleep(10); + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java new file mode 100644 index 0000000000..63446f583d --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.migration.junit4; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +public class AssertionsExampleUnitTest { + @Test + @Ignore + public void shouldFailBecauseTheNumbersAreNotEqualld() { + assertEquals("Numbers are not equal!", 2, 3); + } + + @Test + public void shouldAssertAllTheGroup() { + List list = Arrays.asList(1, 2, 3); + assertEquals("List is not incremental", list.get(0) + .intValue(), 1); + assertEquals("List is not incremental", list.get(1) + .intValue(), 2); + assertEquals("List is not incremental", list.get(2) + .intValue(), 3); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java new file mode 100644 index 0000000000..6022de123f --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.migration.junit4; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RunWith(JUnit4.class) +public class BeforeAndAfterAnnotationsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(BeforeAndAfterAnnotationsUnitTest.class); + + private List list; + + @Before + public void init() { + LOG.info("startup"); + list = new ArrayList<>(Arrays.asList("test1", "test2")); + } + + @After + public void teardown() { + LOG.info("teardown"); + list.clear(); + } + + @Test + public void whenCheckingListSize_thenSizeEqualsToInit() { + LOG.info("executing test"); + assertEquals(2, list.size()); + + list.add("another test"); + } + + @Test + public void whenCheckingListSizeAgain_thenSizeEqualsToInit() { + LOG.info("executing another test"); + assertEquals(2, list.size()); + + list.add("yet another test"); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java new file mode 100644 index 0000000000..8a82a75d3d --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.migration.junit4; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RunWith(JUnit4.class) +public class BeforeClassAndAfterClassAnnotationsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(BeforeClassAndAfterClassAnnotationsUnitTest.class); + + @BeforeClass + public static void setup() { + LOG.info("startup - creating DB connection"); + } + + @AfterClass + public static void tearDown() { + LOG.info("closing DB connection"); + } + + @Test + public void simpleTest() { + LOG.info("simple test"); + } + + @Test + public void anotherSimpleTest() { + LOG.info("another simple test"); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java new file mode 100644 index 0000000000..969d1b370e --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.migration.junit4; + +import org.junit.Rule; +import org.junit.Test; + +import com.baeldung.migration.junit4.rules.TraceUnitTestRule; + +public class RuleExampleUnitTest { + + @Rule + public final TraceUnitTestRule traceRuleTests = new TraceUnitTestRule(); + + @Test + public void whenTracingTests() { + System.out.println("This is my test"); + /*...*/ + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java new file mode 100644 index 0000000000..a2b1b6bdd3 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java @@ -0,0 +1,5 @@ +package com.baeldung.migration.junit4.categories; + +public interface Annotations { + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java new file mode 100644 index 0000000000..dc5d4349f3 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java @@ -0,0 +1,5 @@ +package com.baeldung.migration.junit4.categories; + +public interface JUnit4UnitTest { + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java new file mode 100644 index 0000000000..5c993f17fd --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java @@ -0,0 +1,35 @@ +package com.baeldung.migration.junit4.rules; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.MultipleFailureException; +import org.junit.runners.model.Statement; + +public class TraceUnitTestRule implements TestRule { + + @Override + public Statement apply(Statement base, Description description) { + + return new Statement() { + @Override + public void evaluate() throws Throwable { + List errors = new ArrayList(); + + System.out.println("Starting test ... " + description.getMethodName()); + try { + base.evaluate(); + } catch (Throwable e) { + errors.add(e); + } finally { + System.out.println("... test finished. " + description.getMethodName()); + } + + MultipleFailureException.assertEmpty(errors); + } + }; + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java new file mode 100644 index 0000000000..c2bbfd4d07 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.migration.junit5; + +import java.time.Duration; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@Tag("annotations") +@Tag("junit5") +@RunWith(JUnitPlatform.class) +public class AnnotationTestExampleUnitTest { + @Test + public void shouldRaiseAnException() throws Exception { + Assertions.assertThrows(Exception.class, () -> { + throw new Exception("This is my expected exception"); + }); + } + + @Test + @Disabled + public void shouldFailBecauseTimeout() throws InterruptedException { + Assertions.assertTimeout(Duration.ofMillis(1), () -> Thread.sleep(10)); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java new file mode 100644 index 0000000000..c35611aad1 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.migration.junit5; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +public class AssertionsExampleUnitTest { + @Test + @Disabled + public void shouldFailBecauseTheNumbersAreNotEqual() { + Assertions.assertEquals(2, 3, "Numbers are not equal!"); + } + + @Test + @Disabled + public void shouldFailBecauseItsNotTrue_overloading() { + Assertions.assertTrue(() -> { + return false; + }, () -> "It's not true!"); + } + + @Test + public void shouldAssertAllTheGroup() { + List list = Arrays.asList(1, 2, 3); + + Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0) + .intValue(), 1), () -> Assertions.assertEquals( + list.get(1) + .intValue(), + 2), + () -> Assertions.assertEquals(list.get(2) + .intValue(), 3)); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java new file mode 100644 index 0000000000..80201a3f44 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.migration.junit5; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.Assumptions.assumingThat; + +import org.junit.jupiter.api.Test; + +public class AssumptionUnitTest { + + @Test + public void trueAssumption() { + assumeTrue(5 > 1, () -> "5 is greater the 1"); + assertEquals(5 + 2, 7); + } + + @Test + public void falseAssumption() { + assumeFalse(5 < 1, () -> "5 is less then 1"); + assertEquals(5 + 2, 7); + } + + @Test + public void assumptionThat() { + String someString = "Just a string"; + assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4)); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java new file mode 100644 index 0000000000..b81e9b7b8e --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.migration.junit5; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RunWith(JUnitPlatform.class) +public class BeforeAllAndAfterAllAnnotationsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(BeforeAllAndAfterAllAnnotationsUnitTest.class); + + @BeforeAll + public static void setup() { + LOG.info("startup - creating DB connection"); + } + + @AfterAll + public static void tearDown() { + LOG.info("closing DB connection"); + } + + @Test + public void simpleTest() { + LOG.info("simple test"); + } + + @Test + public void anotherSimpleTest() { + LOG.info("another simple test"); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java new file mode 100644 index 0000000000..f0093b3bf6 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.migration.junit5; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RunWith(JUnitPlatform.class) +public class BeforeEachAndAfterEachAnnotationsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(BeforeEachAndAfterEachAnnotationsUnitTest.class); + + private List list; + + @BeforeEach + public void init() { + LOG.info("startup"); + list = new ArrayList<>(Arrays.asList("test1", "test2")); + } + + @AfterEach + public void teardown() { + LOG.info("teardown"); + list.clear(); + } + + @Test + public void whenCheckingListSize_ThenSizeEqualsToInit() { + LOG.info("executing test"); + assertEquals(2, list.size()); + + list.add("another test"); + } + + @Test + public void whenCheckingListSizeAgain_ThenSizeEqualsToInit() { + LOG.info("executing another test"); + assertEquals(2, list.size()); + + list.add("yet another test"); + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java new file mode 100644 index 0000000000..7b1bcda730 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.migration.junit5; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.baeldung.migration.junit5.extensions.TraceUnitExtension; + +@RunWith(JUnitPlatform.class) +@ExtendWith(TraceUnitExtension.class) +public class RuleExampleUnitTest { + + @Test + public void whenTracingTests() { + System.out.println("This is my test"); + /*...*/ + } +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java new file mode 100644 index 0000000000..db5d3e2573 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java @@ -0,0 +1,19 @@ +package com.baeldung.migration.junit5.extensions; + +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +public class TraceUnitExtension implements AfterEachCallback, BeforeEachCallback { + + @Override + public void beforeEach(ExtensionContext context) throws Exception { + System.out.println("Starting test ... " + context.getDisplayName()); + } + + @Override + public void afterEach(ExtensionContext context) throws Exception { + System.out.println("... test finished. " + context.getDisplayName()); + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java new file mode 100644 index 0000000000..eb8cab2462 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.resourcedirectory; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class ReadResourceDirectoryUnitTest { + + @Test + public void givenResourcePath_whenReadAbsolutePathWithFile_thenAbsolutePathEndsWithDirectory() { + String path = "src/test/resources"; + + File file = new File(path); + String absolutePath = file.getAbsolutePath(); + + System.out.println(absolutePath); + Assert.assertTrue(absolutePath.endsWith("src" + File.separator + "test" + File.separator + "resources")); + } + + @Test + public void givenResourcePath_whenReadAbsolutePathWithPaths_thenAbsolutePathEndsWithDirectory() { + Path resourceDirectory = Paths.get("src", "test", "resources"); + + String absolutePath = resourceDirectory.toFile().getAbsolutePath(); + + System.out.println(absolutePath); + Assert.assertTrue(absolutePath.endsWith("src" + File.separator + "test" + File.separator + "resources")); + } + + @Test + public void givenResourceFile_whenReadResourceWithClassLoader_thenPathEndWithFilename() { + String resourceName = "example_resource.txt"; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource(resourceName).getFile()); + String absolutePath = file.getAbsolutePath(); + + System.out.println(absolutePath); + Assert.assertTrue(absolutePath.endsWith(File.separator + "example_resource.txt")); + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java new file mode 100644 index 0000000000..30b92ad428 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java @@ -0,0 +1,12 @@ +package com.baeldung.suites; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@SelectPackages("com.baeldung") +// @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) +public class AllUnitTest { + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOIntegrationTest.java b/testing/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOIntegrationTest.java new file mode 100644 index 0000000000..7f0720b96d --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOIntegrationTest.java @@ -0,0 +1,69 @@ +package com.baeldung.tags; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.junit.tags.example.Employee; +import com.baeldung.junit.tags.example.EmployeeDAO; +import com.baeldung.junit.tags.example.SpringJdbcConfig; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) +public class EmployeeDAOIntegrationTest { + + @Autowired + private EmployeeDAO employeeDao; + + @Mock + private JdbcTemplate jdbcTemplate; + private EmployeeDAO employeeDAO; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + employeeDAO = new EmployeeDAO(); + employeeDAO.setJdbcTemplate(jdbcTemplate); + } + + @Test + @Tag("IntegrationTest") + public void testAddEmployeeUsingSimpelJdbcInsert() { + final Employee emp = new Employee(); + emp.setId(12); + emp.setFirstName("testFirstName"); + emp.setLastName("testLastName"); + emp.setAddress("testAddress"); + + Assertions.assertEquals(employeeDao.addEmplyeeUsingSimpelJdbcInsert(emp), 1); + } + + @Test + @Tag("UnitTest") + public void givenNumberOfEmployeeWhenCountEmployeeThenCountMatch() { + + // given + Mockito.when(jdbcTemplate.queryForObject(Mockito.any(String.class), Mockito.eq(Integer.class))) + .thenReturn(1); + + // when + int countOfEmployees = employeeDAO.getCountOfEmployees(); + + // then + Assertions.assertEquals(1, countOfEmployees); + } + +} diff --git a/testing/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java b/testing/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java new file mode 100644 index 0000000000..783e5a81a2 --- /dev/null +++ b/testing/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java @@ -0,0 +1,12 @@ +package com.baeldung.tags; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.IncludeTags; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@SelectPackages("com.baeldung.tags") +@IncludeTags("UnitTest") +public class EmployeeDAOTestSuite { +} diff --git a/testing/junit-5-basics/src/test/resources/example_resource.txt b/testing/junit-5-basics/src/test/resources/example_resource.txt new file mode 100644 index 0000000000..e69de29bb2