Skip to content

Instantly share code, notes, and snippets.

@rschumm
Last active August 29, 2015 13:56
Show Gist options
  • Save rschumm/8913517 to your computer and use it in GitHub Desktop.
Save rschumm/8913517 to your computer and use it in GitHub Desktop.
Ganz einfacher DB Integrations-Test
package com.axa.ch.apc.util;
import static org.junit.Assert.assertEquals;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Before;
import org.junit.Test;
public class DataBaseIntTest {
private Connection conn;
@Before
public void initDb() throws SQLException, ClassNotFoundException {
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:~/datenbanken/H2/apc;AUTO_SERVER=TRUE", "root", "1234");
String sqlFileName = "/testdaten.sql";
RunScript.execute(conn, new InputStreamReader(this.getClass().getResourceAsStream(sqlFileName)));
//loadSQLFile(conn, sqlFileName);
}
@Test
public void testDBBaureihe() throws SQLException {
Statement read = conn.createStatement();
ResultSet resultSet = read.executeQuery("select * from remy");
resultSet.next();
assertEquals(2, resultSet.getInt("baureihe"));
}
private void loadSQLFile(Connection conn, String sqlFileName) throws SQLException {
//Diese Methode ist ein böser Häck.
Statement insertStatement = conn.createStatement();
String path = getClass().getResource("/" + sqlFileName).getFile();
if(System.getProperty("os.name").contains("Windows")){
path = path.substring(1);
}
String insert = "RUNSCRIPT FROM '" + path + "';";
insertStatement.execute(insert);
}
}
drop all objects;
-- oder: create table if not exists remy
create table remy
(
baureihe int
);
insert into REMY values (2);
@rschumm
Copy link
Author

rschumm commented Feb 10, 2014

um das File relativ aus dem Testresourcen-Ordner zu lesen, kann dieser Häck gebraucht werden:

    Statement insertStatement = conn.createStatement();

    String path = getClass().getResource("/" + sqlFileName).getFile();
    if(System.getProperty("os.name").contains("Windows")){
        path = path.substring(1);
    }

    String insert = "RUNSCRIPT FROM '" + path + "';";
    insertStatement.execute(insert);

@rschumm
Copy link
Author

rschumm commented Feb 10, 2014

Und noch viel einfacher:

    String sqlFileName = "/testdaten.sql";

    RunScript.execute(conn, new InputStreamReader(this.getClass().getResourceAsStream(sqlFileName))); 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment