#Help with Testing - JAVA - H2

1 messages · Page 1 of 1 (latest)

heady moonBOT
#

<@&987246584574140416> please have a look, thanks.

azure blade
#

please specify "some problem"

#

provide related code and error messages/explain whats not working

untold junco
#

And it's also worth looking into testcontainers over H2 to better represent your actual setup.

rocky phoenix
#

package se.fredrik.databashantering.DAO;

import org.junit.jupiter.api.*;
import se.fredrik.databashantering.Tools.JDBCUtility;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

class DAOImplicatorTest {
private static Connection connection;

@BeforeAll
static void setUp() {
    // Ladda test.properties för H2-databasen
    JDBCUtility.loadProperties("test.properties");

    try {
        connection = JDBCUtility.getConnection();
        try (Statement stmt = connection.createStatement()) {
            // Skapa tabell för testerna
            stmt.execute("CREATE TABLE work_role (" +
                    "role_id INT PRIMARY KEY AUTO_INCREMENT, " +
                    "title VARCHAR(100), " +
                    "description VARCHAR(255), " +
                    "salary DOUBLE, " +
                    "creation_date DATE)");
        }
    } catch (SQLException e) {
        throw new RuntimeException("Failed to set up the test database: " + e.getMessage());
    }
}

@AfterAll
static void tearDown() throws SQLException {
    JDBCUtility.closeConnection();
}

@Test
void testDatabaseConnection() {
    Assertions.assertNotNull(connection, "Database connection should be established.");
}

}

TEST KLASS

#

jdbc.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false
jdbc.username=sa
jdbc.password=
jdbc.driver=org.h2.Driver


test.properties (file)

heady moonBOT
#

Formatted code is easier to read and does not change its functionality. Fortunately, your IDE can fix this for you.

Windows
IntelliJ Ctrl + Alt + L
eclipse Ctrl + Shift + F

Mac
IntelliJ ⌥ + ⌘ + L
eclipse ⌘ + ⇧ + F

Linux (Ubuntu)
IntelliJ Ctrl + Alt + Windows + L
eclipse Ctrl + Shift + F

For example, you can turn this:java int x=5; if(x==5){ System.out.println( "x is 5" ) ; } Into this:```java
int x = 5;
if (x == 5) {
System.out.println("x is 5");
}

fiery pond
#

ah, that was not what I wanted to do

#

anyway, to properfly format code in discord, please just copy paste this template:

```java
YOUR CODE
```

rocky phoenix
#

Okey

fiery pond
#

If you copy that it will look like so:

YOUR CODE
rocky phoenix
#
package se.fredrik.databashantering.DAO;

import org.junit.jupiter.api.*;
import se.fredrik.databashantering.Tools.JDBCUtility;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

class DAOImplicatorTest {
    private static Connection connection;

    @BeforeAll
    static void setUp() {
        // Ladda test.properties för H2-databasen
        JDBCUtility.loadProperties("test.properties");

        try {
            connection = JDBCUtility.getConnection();
            try (Statement stmt = connection.createStatement()) {
                // Skapa tabell för testerna
                stmt.execute("CREATE TABLE work_role (" +
                        "role_id INT PRIMARY KEY AUTO_INCREMENT, " +
                        "title VARCHAR(100), " +
                        "description VARCHAR(255), " +
                        "salary DOUBLE, " +
                        "creation_date DATE)");
            }
        } catch (SQLException e) {
            throw new RuntimeException("Failed to set up the test database: " + e.getMessage());
        }
    }

    @AfterAll
    static void tearDown() throws SQLException {
        JDBCUtility.closeConnection();
    }

    @Test
    void testDatabaseConnection() {
        Assertions.assertNotNull(connection, "Database connection should be established.");
    }
}

JAVA TEST KLASS

heady moonBOT
# rocky phoenix ```java package se.fredrik.databashantering.DAO; import org.junit.jupiter.api.*...

Detected code, here are some useful tools:

Formatted code
package se.fredrik.databashantering.DAO;

import org.junit.jupiter.api. * ;
import se.fredrik.databashantering.Tools.JDBCUtility;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

class DAOImplicatorTest {
  private static Connection connection;
  @BeforeAll
  static void setUp() {
    // Ladda test.properties för H2-databasen
    JDBCUtility.loadProperties("test.properties");
    try {
      connection = JDBCUtility.getConnection();
      try (Statement stmt = connection.createStatement()) {
        // Skapa tabell för testerna
        stmt.execute("CREATE TABLE work_role (" + "role_id INT PRIMARY KEY AUTO_INCREMENT, " + "title VARCHAR(100), " + "description VARCHAR(255), " + "salary DOUBLE, " + "creation_date DATE)");
      }
    } catch (SQLException e) {
      throw new RuntimeException("Failed to set up the test database: " + e.getMessage());
    }
  }
  @AfterAll
  static void tearDown() throws SQLException {
    JDBCUtility.closeConnection();
  }
  @Test
  void testDatabaseConnection() {
    Assertions.assertNotNull(connection, "Database connection should be established.");
  }
}
rocky phoenix
#
jdbc.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false
jdbc.username=sa
jdbc.password=
jdbc.driver=org.h2.Driver 

test.properties

heady moonBOT
rocky phoenix
#
 public static void loadProperties (String fileName) {
        try (InputStream input = JDBCUtility.class.getClassLoader().getResourceAsStream(fileName)) {
            if (input == null) {
                throw new IOException("Kunde ej hitta properties filen" + fileName);
            }
            properties.load(input);

            DATABAS_URL = properties.getProperty("db.url");
            DATABASE_USER = properties.getProperty("db.user");
            DATABASE_PASSWORD = properties.getProperty("db.password");

        }
        catch (IOException e){
            throw new ExceptionInInitializerError("Could not find the application.properties file" + e);
        }
    }

JBCUtil class

heady moonBOT
# rocky phoenix ```java public static void loadProperties (String fileName) { try (Inpu...

Detected code, here are some useful tools:

Formatted code
public static void loadProperties(String fileName) {
  try (InputStream input = JDBCUtility.class .getClassLoader().getResourceAsStream(fileName)) {
    if (input == null ) {
      throw new IOException("Kunde ej hitta properties filen" + fileName);
    }
    properties.load(input);
    DATABAS_URL = properties.getProperty("db.url");
    DATABASE_USER = properties.getProperty("db.user");
    DATABASE_PASSWORD = properties.getProperty("db.password");
  } catch (IOException e) {
    throw new ExceptionInInitializerError("Could not find the application.properties file" + e);
  }
}
rocky phoenix
#

Anything else you need?

fiery pond
rocky phoenix
#

Yeah, sorry:

this is the error message i get when i try to run the code

Test ignored.

java.lang.RuntimeException: Failed to set up the test database: The url cannot be null

fiery pond
rocky phoenix
#

The connection class it self is working when am connecting to my MySQL server through main

fiery pond
#

[Is] it the connection = JDBCUtility.getConnection();, the Statement stmt = connection.createStatement() or the stmt.execute(...)?

rocky phoenix
fiery pond
rocky phoenix
#

Tried with this small test and this is the error i get.
Can I get more error code then this?

#

Its saying that the properties file is NULL, might this be the issue?

fiery pond
rocky phoenix
#

Okey

#

I'll get keep error searching then i hope someone else come that knows ^^

#

The H2 server connection and the driver is working as it should.
It's just that I got problems adding a propertiesfiles to resources folder and loading that

heady moonBOT
#

@rocky phoenix

Your question has been closed due to inactivity.

If it was not resolved yet, feel free to just post a message below
to reopen it, or create a new thread.

Note that usually the reason for nobody calling back is that your
question may have been not well asked and hence no one felt confident
enough answering.

When you reopen the thread, try to use your time to improve the quality
of the question by elaborating, providing details, context, all relevant code
snippets, any errors you are getting, concrete examples and perhaps also some
screenshots. Share your attempt, explain the expected results and compare
them to the current results.

Also try to make the information easily accessible by sharing code
or assignment descriptions directly on Discord, not behind a link or
PDF-file; provide some guidance for long code snippets and ensure
the code is well formatted and has syntax highlighting. Kindly read through
https://stackoverflow.com/help/how-to-ask for more.

With enough info, someone knows the answer for sure 👍

rocky phoenix
#

Not solved

#

Still need help

untold junco
#

Can you show your test folder?

jolly cedar
#

@rocky phoenix A few things

#

and i am fully aware that this is probably just how your school showed you how to do this stuff

#

but we gotta work backwards to get you to a sane place

#

don't bother with h2

#

use your real database

#
  1. That JDBCUtility is not what you need. You need a DataSource
#

I have an example of using a database "properly" in java here - though I didn't write any db test code unfortunately (would be a decent example)

#

all that is to say - the more code you share the easier it is to help with this

#

since the right answer is gonna take some tweaking

#

oh and

#
String s = """
   You can have
   strings that go over
   multiple
   lines
   """;
rocky phoenix
#

I get that.
Already got a connection to a mysql server that works.

The requirements are for a h2 test server with a properties file in test/resources

#

Everything works apart from me getting access to the properties file in the test.

And I don't get why

#

Got school during the day now. But can post later 😊

rocky phoenix
#

SAVE:

YOUR CODE
#
package se.fredrik.databashantering.Tools;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;


//! Hjälp klass för att koppla sig mot servern
public class JDBCUtility {

    //! Attribut
    //! Information från application.properties filen

    private static Properties properties = new Properties();

    //! Attribut för att koppla mig mot servern
    private static String DATABAS_URL;
    private static String DATABASE_USER;
    private static String DATABASE_PASSWORD;

    //! Metod för att skapa en koppling mot servern
    //! Drivern är för att koppla sig mot min MySQL server

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DATABAS_URL, DATABASE_USER, DATABASE_PASSWORD);
    }

    //! Static metod för att hämta information från application.properties filen till servern
    //! Generisk för att användas både i produktion och i test

    public static void loadProperties (String fileName) {
        try (InputStream input = JDBCUtility.class.getClassLoader().getResourceAsStream(fileName)) {
            if (input == null) {
                throw new IOException("Kunde ej hitta properties filen" + fileName);
            }
            properties.load(input);

            DATABAS_URL = properties.getProperty("db.url");
            DATABASE_USER = properties.getProperty("db.user");
            DATABASE_PASSWORD = properties.getProperty("db.password");

        }
        catch (IOException e){
            throw new ExceptionInInitializerError("Could not find the application.properties file" + e);
        }
    }

}

JBCU Util CLASS

#
package se.fredrik.databashantering.DAO;


import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import se.fredrik.databashantering.JobHive.WorkRole;
import org.junit.jupiter.api.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;


import java.sql.*;

import static org.junit.Assert.*;

public class InsertThenGetAllWorkRolesTEST {
    private static Connection connection;
    private static DAOImplicator dao;


    @BeforeAll
    static void startUp() throws SQLException {
        //! Använd H2-servern för att göra testet
        connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", "");

        //! Skapa en ny dao och använd kopplingen du precis har skapat ovan
        dao = new DAOImplicator(connection);

        try (Statement statement = connection.createStatement()) {
            statement.execute("""
                         CREATE TABLE IF NOT EXISTS work_role (
                         role_id INT AUTO_INCREMENT PRIMARY KEY,
                         title VARCHAR(50),
                         description VARCHAR(50),
                           salary DOUBLE,
                           creation_date DATE
                         )
                         """);
        }
    }

    @Test
    void insertWorkRoleAndTryRecievingThem() throws SQLException {
        //! Skapa en ny workrole in i tabellen

        WorkRole workRole1 = new WorkRole ("Programmer", "Useful Guy", 50000, new java.sql.Date(System.currentTimeMillis()));
        WorkRole workRole2 = new WorkRole ("UX-Designer", "Cool Guy", 10000, new java.sql.Date(System.currentTimeMillis()));

        //! Lägg in WorkRoles
        dao.insertWorkRole(workRole1);
        dao.insertWorkRole(workRole2);

        //! Hämta ut alla WorkRoles
        List<WorkRole> workRoles = dao.getAllWorkRoles();
        // Använd forEach direkt för att skriva ut formaterad text
        workRoles.stream()
                .forEach(role -> System.out.println("""
                 Title: %s
                 Description: %s
                 Salary: %s
                 CreationDate: %s
                 """.formatted(role.getTitle(),
                        role.getDescription(),
                        role.getSalary(),
                        role.getCreationDate())));

        //! Kör själva testet och kolla att allt fungerar som det ska


        //? Kontrollera om det faktiskt finns två WorkRoles i listan eller inte
        assertEquals(2, workRoles.size());

        //? Kontrollera att det faktiskt finns workRoles med namnet Programmer och UX-Designer
        //? Använder mig av stream för att kolla igenom listan

        assertTrue(workRoles.stream().anyMatch(role -> "Programmer".equalsIgnoreCase(role.getTitle())));
        assertTrue(workRoles.stream().anyMatch(role -> "UX-Designer".equalsIgnoreCase(role.getTitle())));

        //? Testar med ett test för skojs skull där jag testar en falsk boolean

        Assertions.assertFalse(workRoles.stream().anyMatch(role -> "Speldesigner".equalsIgnoreCase(role.getTitle())));

    }

    //? Rensar databasen efter varje test
    @AfterEach
    void cleanDatabase() throws SQLException {
        try (Statement statement = connection.createStatement()) {
            statement.execute("TRUNCATE TABLE work_role");
        }
    }

    //! Stänger kopplingen när allt är klart
    @AfterAll
    static void closeConnection() throws SQLException {
        if (connection != null) {
            connection.close();
        }

    }
}

TEST CLASS

#
jdbc.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false
jdbc.username=sa
jdbc.password=
jdbc.driver=org.h2.Driver 

test.properties file am trying to reach

#
package se.fredrik.databashantering.DAO;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesFileTest {

    private static String DATABAS_URL;
    private static String DATABASE_USER;
    private static String DATABASE_PASSWORD;
    private static Properties properties = new Properties();

    public static void loadProperties(String fileName) throws IOException {
        // Load the properties file from the classpath
        try (InputStream input = PropertiesFileTest.class.getClassLoader().getResourceAsStream(fileName)) {
            if (input == null) {
                throw new IOException("Kunde ej hitta properties filen: " + fileName);
            }
            // Load properties from the input stream
            properties.load(input);

            // Get properties for DB connection
            DATABAS_URL = properties.getProperty("db.url");
            DATABASE_USER = properties.getProperty("db.user");
            DATABASE_PASSWORD = properties.getProperty("db.password");

        } catch (IOException e) {
            throw new IOException("Could not load properties file: " + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        try {
            // Load properties from the "test.properties" file
            loadProperties("test.properties");
        } catch (IOException e) {
            System.out.println("Kunde ej ladda properties filen: " + e.getMessage());
            return;
        }

        // Output the database connection details
        System.out.println("Database URL: " + DATABAS_URL);
        System.out.println("Database User: " + DATABASE_USER);
    }
}

Test file to test the properties file.
Returns null

#

Anything else you need @jolly cedar ?

jolly cedar
#

Ehhh

#

Well no but

rocky phoenix
#

test.properties file in in the test location under resources

jolly cedar
#

Can you just share the whole repo?

#

Basically running the project locally is always easiest

#

And I probably won't be the one to go through this

#

I'm just telling you what is needed to debug your issue

rocky phoenix
#

Guess I'll just wait for someone else again i guess..

#

If someone wants the repo I can share it on GitHub, just send me a private message

untold junco
#

Being able to run it would be easier, also you have DATABAS_URL rather than DATABASE_URL and where are you even calling your load function? Also just share it here, no need to add extra hurdles for helpers.