Java Reference
In-Depth Information
Hibernate's Session or JPA 's EntityManager ) into the test cases, which can also be
done through the use of annotations.
The dbunit module works similarly to the infrastructure provided in chapter 17:
you mark the test methods with annotations ( @DataSet and/or @ExpectedDataSet ),
and Unitils takes care of preparing the database or asserting its content with the data-
set defined by these annotations. The main differences are where the datasets are
located (relative to the class's package directory in the classpath) and also the fact that
the annotations could be defined at class or method levels (class level is useful when
many methods use the same dataset; individual methods could then override it by
using the annotation again with different values).
In chapter 17 we used DbUnit to test a JDBC -based DAO , and in chapter 18 we used
it to test a JPA -based DAO that used Hibernate as the JPA implementation. Let's rewrite
these two test cases using Unitils, starting with the JDBC version in listing 19.5.
Listing 19.5
Refactored UserDaoJdbcImplTest using Unitils
[...]
import static com.manning.junitbook.ch19.model.EntitiesHelper.*;
import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;
import org.unitils.UnitilsJUnit4;
import org.unitils.database.annotations.TestDataSource;
import org.unitils.dbunit.annotation.DataSet;
import org.unitils.dbunit.annotation.ExpectedDataSet;
B
public class UserDaoJdbcImplTest extends UnitilsJUnit4 {
private UserDaoJdbcImpl dao = new UserDaoJdbcImpl();
@TestDataSource
void setDataSource(DataSource ds) throws SQLException {
Connection connection = ds.getConnection();
dao.setConnection(connection);
dao.createTables();
}
C
@Test
@DataSet("user.xml")
public void testGetUserById() throws Exception {
long id = 1;
User user = dao.getUserById(id);
assertUser(user);
}
D
@Test
@DataSet("user.xml")
public void testGetUserByIdUnknowId() throws Exception {
long id = 2;
 
 
 
Search WWH ::




Custom Search