Issue
So I have a test set up like this:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.sam.demo.HibernateUtil;
import com.sam.entity.Student;
public class HibernateTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeAll
public static void setup() {
sessionFactory = HibernateUtil.getSessionFactory();
}
@AfterAll
public static void teardown() {
sessionFactory.close();
}
@BeforeEach
public void openSession() {
session = sessionFactory.getCurrentSession();
}
@AfterEach
public void closeSession() {
session.close();
}
@Test
@DisplayName("Create student in the database")
public void testCreate() {
try {
Student student = new Student("Angela", "Wu", "[email protected]");
session.beginTransaction();
Integer id = (Integer) session.save(student);
session.getTransaction().commit();
Assertions.assertTrue(id > 0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I was running this test after dropping the table manually to see what result I would get. The record could not be inserted into the database because the table did not exist and I got an exception, but I was surprised to see that my test passed! can someone help me with this? I thought that the save() method won't return anything and the id won't be > 0.
My hibernate configuration is:
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/student_tracker?useSSL=false&serverTimezone=UTC
</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="current_session_context_class">thread</property>
<mapping class="com.sam.entity.Student" />
</session-factory>
</hibernate-configuration>
Solution
You never reached your Assertions.assertTrue(id > 0);
statement.
As the db table was missing, commit
threw an exception.
You handled the exception by printing the stack trace to the console.
To let the test fail you can:
- rethrow the exception
- drop the exception handling
Your handler only prints the stack trace, but test runner does the same for uncaught exceptions, so I would go with the latter option.
As a side note, if you need to handle an exception, try to be as specific as possible - catching Exception
is rarely a good idea, as it can hide unexpected ones.
Answered By - Lesiak
Answer Checked By - Marie Seifert (JavaFixing Admin)