Reputation: 6677
first of all thank you all for reading this. i want to populate my database (derby) every time i run the test class to be able to perform test like delete or update or deletebyid stuffs. I use
<property name="hibernate.hbm2ddl.auto">create</property>
in my hibernate.cfg.xml file so i'm expecting the database to be first drop and created each time i run the test. i used the class constructor or setup methods but soon realized that they are called the number of time there is a test method in the class (i assume the beforetest and the rest behave the same). So my question is how do i setup the initial data to work with? thanks for reading.
Upvotes: 0
Views: 1440
Reputation: 13724
For the initial data setup (using the annotations described by Dirk), I've used two different methods. If I really want to test the entire process including the ddl script, I have my BeforeClass completely recreate the database by exec'ing an OS process and running the appropriate command to drop and create for that database type. But most of the time I just clear out the tables at the beginning and end of each test (or class) using Hibernate or SQL deletes. That doesn't test the ddl creation part, but usually the Hibernate configuration and other tests will indicate if your database schema is wrong anyway.
Upvotes: 0
Reputation: 30448
Take a look at DbUnit, it's a JUnit extension aimed to ease db based application testing. One of its features is to have a pre-defined datasets, which populate the database on the beginning of the test. See more here - http://www.dbunit.org/components.html#dataset
Upvotes: 3
Reputation: 31053
Assuming JUnit 4: There are two groups of annotations, which can be used to trigger the execution of code before and after running the actual test case method(s):
Before
Methods annotated with this marker are executed by the JUnit framework before it calls the next test case method.
After
Methods annotated with this marker are executed by JUnit after the actual test case method has been run.
BeforeClass
Methods marked with this annotation will be executed only once (before JUnit runs the first test case). If I read your post correctly, this is the option you actually want.
AfterClass
Methods tagged with this annotation will be executed only once (after JUnit has run the last test case).
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class SomeTest {
@Test
public void test1() {
System.out.println("test1");
}
@Test
public void test2() {
System.out.println("test2");
}
@Before
public void setUp() {
// Here goes the code, which makes sure, all tests
// see the same context
System.out.println("setUp");
}
@BeforeClass
public static void setUpGlobals() {
// Expensive hibernate set-up will go here. It is
// called only once
System.out.println("setUpGlobals");
}
}
will produce the output
Upvotes: 1