Adding a test to demonstrate programmatic registration.

This commit is contained in:
Ali Dehghani 2019-05-10 21:45:29 +04:30
parent 97022ca7d3
commit 0dd99df208
2 changed files with 52 additions and 2 deletions

View File

@ -0,0 +1,42 @@
package com.baeldung;
import java.sql.SQLException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import com.baeldung.helpers.Employee;
import com.baeldung.extensions.EmployeeDaoParameterResolver;
import com.baeldung.extensions.EmployeeDatabaseSetupExtension;
import com.baeldung.extensions.EnvironmentExtension;
import com.baeldung.helpers.EmployeeJdbcDao;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith({ EnvironmentExtension.class, EmployeeDaoParameterResolver.class })
public class ProgrammaticEmployeesUnitTest {
private EmployeeJdbcDao employeeDao;
@RegisterExtension static EmployeeDatabaseSetupExtension DB =
new EmployeeDatabaseSetupExtension("jdbc:h2:mem:AnotherDb;DB_CLOSE_DELAY=-1", "org.h2.Driver", "sa", "");
public ProgrammaticEmployeesUnitTest(EmployeeJdbcDao employeeDao) {
this.employeeDao = employeeDao;
}
@Test
public void whenAddEmployee_thenGetEmployee() throws SQLException {
Employee emp = new Employee(1, "john");
employeeDao.add(emp);
assertEquals(1, employeeDao.findAll()
.size());
}
@Test
public void whenGetEmployees_thenEmptyList() throws SQLException {
assertEquals(0, employeeDao.findAll()
.size());
}
}

View File

@ -11,7 +11,7 @@ public class JdbcConnectionUtil {
private static Connection con; private static Connection con;
public static Connection getConnection() { public static Connection getConnection() {
if (con == null) { if (con == null || isClosed(con)) {
try { try {
Properties props = new Properties(); Properties props = new Properties();
props.load(JdbcConnectionUtil.class.getResourceAsStream("jdbc.properties")); props.load(JdbcConnectionUtil.class.getResourceAsStream("jdbc.properties"));
@ -32,7 +32,7 @@ public class JdbcConnectionUtil {
} }
public static Connection getConnection(String jdbcUrl, String driver, String username, String password) { public static Connection getConnection(String jdbcUrl, String driver, String username, String password) {
if (con == null) { if (con == null || isClosed(con)) {
try { try {
Class.forName(driver); Class.forName(driver);
con = DriverManager.getConnection(jdbcUrl, username, password); con = DriverManager.getConnection(jdbcUrl, username, password);
@ -48,4 +48,12 @@ public class JdbcConnectionUtil {
return con; return con;
} }
private static boolean isClosed(Connection con) {
try {
return con.isClosed();
} catch (SQLException e) {
return true;
}
}
} }