junit 5 example (#2050)

This commit is contained in:
lor6 2017-06-12 11:20:42 +03:00 committed by Eugen
parent 080a4234a9
commit b6d47b00a3
12 changed files with 582 additions and 0 deletions

4
guest/junit5-example/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/target/
.settings/
.classpath
.project

View File

@ -0,0 +1,68 @@
<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>
<groupId>junit5-example</groupId>
<artifactId>junit5-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.0.0-M4</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.0.0-M4</version>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>4.12.0-M4</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.195</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.0.0-M4</version>
</dependency>
</dependencies>
<configuration>
<properties>
<excludeTags>math</excludeTags>
</properties>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,141 @@
package com.stackify.daos;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.stackify.models.User;
import com.stackify.utils.ConnectionUtil;
public class UserDAO {
private Logger logger = LogManager.getLogger(UserDAO.class);
public void createTable() {
try (Connection con = ConnectionUtil.getConnection()) {
String createQuery = "CREATE TABLE users(email varchar(50) primary key, name varchar(50))";
PreparedStatement pstmt = con.prepareStatement(createQuery);
pstmt.execute();
} catch (SQLException exc) {
logger.error(exc.getMessage());
}
}
public void add(User user) {
try (Connection con = ConnectionUtil.getConnection()) {
String insertQuery = "INSERT INTO users(email,name) VALUES(?,?)";
PreparedStatement pstmt = con.prepareStatement(insertQuery);
pstmt.setString(1, user.getEmail());
pstmt.setString(2, user.getName());
pstmt.executeUpdate();
} catch (SQLException exc) {
logger.error(exc.getMessage());
}
}
public void update(User user) {
try (Connection con = ConnectionUtil.getConnection()) {
String updateQuery = "UPDATE users SET name=? WHERE email=?";
PreparedStatement pstmt = con.prepareStatement(updateQuery);
pstmt.setString(1, user.getName());
pstmt.setString(2, user.getEmail());
pstmt.executeUpdate();
} catch (SQLException exc) {
logger.error(exc.getMessage());
}
}
public void delete(User user) {
try (Connection con = ConnectionUtil.getConnection()) {
String deleteQuery = "DELETE FROM users WHERE email=?";
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
pstmt.setString(1, user.getEmail());
pstmt.executeUpdate();
} catch (SQLException exc) {
logger.error(exc.getMessage());
}
}
public void delete(String email) {
try (Connection con = ConnectionUtil.getConnection()) {
String deleteQuery = "DELETE FROM users WHERE email=?";
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
pstmt.setString(1, email);
pstmt.executeUpdate();
} catch (SQLException exc) {
logger.error(exc.getMessage());
}
}
public User findOne(String email) {
User user = null;
try (Connection con = ConnectionUtil.getConnection()) {
String query = "SELECT * FROM users WHERE email=?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, email);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
user = new User();
user.setEmail(rs.getString("email"));
user.setName(rs.getString("name"));
}
} catch (SQLException exc) {
logger.error(exc.getMessage());
}
return user;
}
public List<User> findAll() {
List<User> users = new ArrayList<>();
try (Connection con = ConnectionUtil.getConnection()) {
String query = "SELECT * FROM users";
PreparedStatement pstmt = con.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
User user = new User();
user.setEmail(rs.getString("email"));
user.setName(rs.getString("name"));
users.add(user);
}
} catch (SQLException exc) {
logger.error(exc.getMessage());
}
return users;
}
public void deleteAll() {
try (Connection con = ConnectionUtil.getConnection()) {
String deleteQuery = "DELETE FROM users";
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
pstmt.executeUpdate();
} catch (SQLException exc) {
logger.error(exc.getMessage());
}
}
}

View File

@ -0,0 +1,63 @@
package com.stackify.models;
public class User {
private String email;
private String name;
public User() {
}
public User(String email, String name) {
super();
this.email = email;
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

View File

@ -0,0 +1,38 @@
package com.stackify.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ConnectionUtil {
private static Logger logger = LogManager.getLogger(ConnectionUtil.class);
public static Connection getConnection() {
try {
Properties props = new Properties();
props.load(ConnectionUtil.class.getResourceAsStream("jdbc.properties"));
Class.forName(props.getProperty("jdbc.driver"));
Connection con = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.user"), props.getProperty("jdbc.password"));
return con;
}
catch (FileNotFoundException exc) {
logger.error(exc.getMessage());
} catch (IOException exc) {
logger.error(exc.getMessage());
} catch (ClassNotFoundException exc) {
logger.error(exc.getMessage());
} catch (SQLException exc) {
logger.error(exc.getMessage());
}
return null;
}
}

View File

@ -0,0 +1,4 @@
jdbc.driver=org.h2.Driver
jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
jdbc.user=
jdbc.password=

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,19 @@
package com.stackify.test;
import java.sql.Connection;
import org.junit.jupiter.api.Test;
import com.stackify.utils.ConnectionUtil;
import static org.junit.jupiter.api.Assertions.*;
public interface DatabaseConnectionTest {
@Test
default void testDatabaseConnection() {
Connection con = ConnectionUtil.getConnection();
assertNotNull(con);
}
}

View File

@ -0,0 +1,38 @@
package com.stackify.test;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.function.ThrowingConsumer;
import com.stackify.daos.UserDAO;
import com.stackify.models.User;
public class DynamicTests {
@TestFactory
public Collection<DynamicTest> dynamicTestCollection() {
return Arrays.asList(DynamicTest.dynamicTest("Dynamic Test", () -> assertTrue(1 == 1)));
}
@TestFactory
public Stream<DynamicTest> dynamicUserTestCollection() {
List<User> inputList = Arrays.asList(new User("john@yahoo.com", "John"), new User("ana@yahoo.com", "Ana"));
Function<User, String> displayNameGenerator = (input) -> "Saving user: " + input;
UserDAO userDAO = new UserDAO();
ThrowingConsumer<User> testExecutor = (input) -> {
userDAO.add(input);
assertNotNull(userDAO.findOne(input.getEmail()));
};
return DynamicTest.stream(inputList.iterator(), displayNameGenerator, testExecutor);
}
}

View File

@ -0,0 +1,25 @@
package com.stackify.test;
import static org.junit.jupiter.api.Assertions.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.RepetitionInfo;
public class IncrementTest {
private static Logger logger = LogManager.getLogger(IncrementTest.class);
@BeforeEach
public void increment() {
logger.info("Before Each Test");
}
@RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)
public void test(RepetitionInfo info) {
assertTrue(1 == 1);
logger.info("Repetition #" + info.getCurrentRepetition());
}
}

View File

@ -0,0 +1,16 @@
package com.stackify.test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@Tag("math")
public class TaggedTest {
@Test
@Tag("arithmetic")
public void testEquals() {
assertTrue(1 == 1);
}
}

View File

@ -0,0 +1,153 @@
package com.stackify.test;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.stackify.daos.UserDAO;
import com.stackify.models.User;
public class UsersTest implements DatabaseConnectionTest {
private static UserDAO userDAO;
private static Logger logger = LogManager.getLogger(UsersTest.class);
@BeforeAll
public static void addData() {
userDAO = new UserDAO();
userDAO.createTable();
User user1 = new User("john@gmail.com", "John");
User user2 = new User("ana@gmail.com", "Ana");
userDAO.add(user1);
userDAO.add(user2);
}
@Test
@DisplayName("Test Get Users")
public void testGetUsersNumber() {
assertEquals(2, userDAO.findAll().size());
}
@Test
@DisplayName("Test Get Users")
public void testGetUsersNumberWithInfo(TestInfo testInfo) {
assertEquals(2, userDAO.findAll().size());
assertEquals("Test Get Users", testInfo.getDisplayName());
assertEquals(UsersTest.class, testInfo.getTestClass().get());
logger.info("Running test method:" + testInfo.getTestMethod().get().getName());
}
@Test
public void testGetUser() {
User user = userDAO.findOne("john@gmail.com");
assertEquals("John", user.getName(), "User name:" + user.getName() + " incorrect");
}
@Test
public void testClassicAssertions() {
User user1 = userDAO.findOne("john@gmail.com");
User user2 = userDAO.findOne("john@yahoo.com");
assertNotNull(user1);
assertNull(user2);
user2 = new User("john@yahoo.com", "John");
assertEquals(user1.getName(), user2.getName(), "Names are not equal");
assertFalse(user1.getEmail().equals(user2.getEmail()), "Emails are equal");
assertNotSame(user1, user2);
}
@Test
@Disabled
public void testGroupedAssertions() {
User user = userDAO.findOne("john@gmail.com");
assertAll("user", () -> assertEquals("Johnson", user.getName()), () -> assertEquals("johnson@gmail.com", user.getEmail()));
}
@Test
public void testIterableEquals() {
User user1 = new User("john@gmail.com", "John");
User user2 = new User("ana@gmail.com", "Ana");
List<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
assertIterableEquals(users, userDAO.findAll());
}
@Test
public void testLinesMatch() {
List<String> expectedLines = Collections.singletonList("(.*)@(.*)");
List<String> emails = Arrays.asList("john@gmail.com");
assertLinesMatch(expectedLines, emails);
}
@Test
void testThrows() {
User user = null;
Exception exception = assertThrows(NullPointerException.class, () -> user.getName());
logger.info(exception.getMessage());
}
@Test
@Disabled
void testFail() {
fail("this test fails");
}
@Test
void testAssumptions() {
List<User> users = userDAO.findAll();
assumeFalse(users == null);
assumeTrue(users.size() > 0);
User user1 = new User("john@gmail.com", "John");
assumingThat(users.contains(user1), () -> assertTrue(users.size() > 1));
}
@ParameterizedTest
@ValueSource(strings = { "john@gmail.com", "ana@gmail.com" })
public void testParameterized(String email) {
assertNotNull(userDAO.findOne(email));
}
@AfterAll
public static void removeData() {
userDAO.deleteAll();
}
@Nested
class DeleteUsersTest {
@Test
public void addUser() {
User user = new User("bob@gmail.com", "Bob");
userDAO.add(user);
assertNotNull(userDAO.findOne("bob@gmail.com"));
userDAO.delete("bob@gmail.com");
assertNull(userDAO.findOne("bob@gmail.com"));
}
}
}