Add Junit5 test base
This commit is contained in:
parent
a5a189d470
commit
9e1f3c0899
|
@ -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)
|
|
@ -0,0 +1,129 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>junit-5-basics</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>junit-5-basics</name>
|
||||
<description>Intro to JUnit 5</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ossez</groupId>
|
||||
<artifactId>testing</artifactId>
|
||||
<version>0.0.2-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-migrationsupport</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-orm</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/test/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>filtering</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.surefire</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
**/*IntegrationTest.java
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>category</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.surefire</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<groups>com.baeldung.categories.UnitTest</groups>
|
||||
<excludedGroups>com.baeldung.categories.IntegrationTest</excludedGroups>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>tags</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.surefire</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<groups>UnitTest</groups>
|
||||
<excludedGroups>IntegrationTest</excludedGroups>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<spring.version>5.0.6.RELEASE</spring.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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<Employee> 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<String, Object> parameters = new HashMap<String, Object>();
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -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<Employee> {
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.junit5;
|
||||
|
||||
public class Greetings {
|
||||
|
||||
public static String sayHello() {
|
||||
return "Hello";
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
CREATE TABLE EMPLOYEE
|
||||
(
|
||||
ID int NOT NULL PRIMARY KEY,
|
||||
FIRST_NAME varchar(255),
|
||||
LAST_NAME varchar(255),
|
||||
ADDRESS varchar(255),
|
||||
);
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
|
||||
>
|
||||
|
||||
<bean id="employeeDao" class="org.baeldung.jdbc.EmployeeDAO">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
</bean>
|
||||
|
||||
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
|
||||
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||
<property name="url" value="${jdbc.url}"/>
|
||||
<property name="username" value="${jdbc.username}"/>
|
||||
<property name="password" value="${jdbc.password}"/>
|
||||
</bean>
|
||||
|
||||
<context:property-placeholder location="jdbc.properties"/>
|
||||
</beans>
|
|
@ -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');
|
|
@ -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<Integer, String> hashmap = new HashMap<>();
|
||||
hashmap.put(1, "One");
|
||||
hashmap.put(2, "Two");
|
||||
|
||||
Executable executable = () -> hashmap.forEach((key, value) -> hashmap.remove(1));
|
||||
assertThrows(ConcurrentModificationException.class, executable);
|
||||
}
|
||||
}
|
|
@ -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<Integer> 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);
|
||||
}
|
||||
}
|
|
@ -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()));
|
||||
}
|
||||
|
||||
}
|
|
@ -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.");
|
||||
}
|
||||
|
||||
}
|
|
@ -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<String> in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No"));
|
||||
private List<String> out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie"));
|
||||
|
||||
@TestFactory
|
||||
public Stream<DynamicTest> 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";
|
||||
}
|
||||
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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 {
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.categories;
|
||||
|
||||
public interface IntegrationTest {
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.categories;
|
||||
|
||||
public interface UnitTest {
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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<String> 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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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<String> 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<String> 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())));
|
||||
}
|
||||
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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()));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.junit5.spring;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class SpringTestConfiguration {
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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<Integer> 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);
|
||||
}
|
||||
}
|
|
@ -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<String> 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");
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
/*...*/
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.migration.junit4.categories;
|
||||
|
||||
public interface Annotations {
|
||||
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.migration.junit4.categories;
|
||||
|
||||
public interface JUnit4UnitTest {
|
||||
|
||||
}
|
|
@ -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<Throwable> errors = new ArrayList<Throwable>();
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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<Integer> 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));
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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<String> 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");
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
/*...*/
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
|
@ -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"));
|
||||
}
|
||||
|
||||
}
|
|
@ -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 {
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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 {
|
||||
}
|
Loading…
Reference in New Issue