org.dbunit.DatabaseUnitException Java Examples

The following examples show how to use org.dbunit.DatabaseUnitException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExportDataSetIt.java    From database-rider with Apache License 2.0 6 votes vote down vote up
@Test
@DataSet(cleanBefore = true)
public void shouldExportYMLDataSetProgrammatically() throws SQLException, DatabaseUnitException {
    tx().begin();
    User u1 = new User();
    u1.setName("u1");
    EntityManagerProvider.em().persist(u1);
    tx().commit();
    DataSetExporter.getInstance().export(emProvider.connection(), new DataSetExportConfig().outputFileName("target/user.yml"));
    File ymlDataSet = new File("target/user.yml");
    assertThat(ymlDataSet).exists();
    assertThat(contentOf(ymlDataSet)).
            contains("USER:" + NEW_LINE +
                            "  - ID: " + u1.getId() + NEW_LINE +
                            "    NAME: \"u1\"" + NEW_LINE
            );
}
 
Example #2
Source File: ExportNullPropertiesIt.java    From database-rider with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotExportNullColumnsInYMLDataSet() throws SQLException, DatabaseUnitException {
    DataSetExporter.getInstance().export(new DatabaseConnection(emProvider.connection()), new DataSetExportConfig().outputFileName("target/userWithNullProperty.yml"));
    File ymlDataSet = new File("target/userWithNullProperty.yml");
    assertThat(ymlDataSet).exists();
    assertThat(contentOf(ymlDataSet)).
            contains("FOLLOWER:" + NEW_LINE +
                            "" + NEW_LINE +
                            "SEQUENCE:" + NEW_LINE +
                            "  - SEQ_NAME: \"SEQ_GEN\"" + NEW_LINE +
                            "    SEQ_COUNT: 50" + NEW_LINE +
                            "" + NEW_LINE +
                            "TWEET:" + NEW_LINE +
                            "" + NEW_LINE +
                            "USER:" + NEW_LINE +
                            "  - ID: 1" + NEW_LINE + NEW_LINE
            );
}
 
Example #3
Source File: NetezzaConnectionFactoryTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateConnection() throws DatabaseUnitException {
    // GIVEN
    final String schema = "foo";

    // WHEN
    final IDatabaseConnection dbConnection = FACTORY.createConnection(connection, schema);

    // THEN
    assertThat(dbConnection, notNullValue());

    final Object typeFactory = dbConnection.getConfig().getProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY);
    assertThat(typeFactory, notNullValue());
    assertThat(typeFactory.getClass(), equalTo(NetezzaDataTypeFactory.class));

    final Object metadataHandler = dbConnection.getConfig().getProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER);
    assertThat(metadataHandler, notNullValue());
    assertThat(metadataHandler.getClass(), equalTo(NetezzaMetadataHandler.class));

    assertThat(dbConnection.getSchema(), equalTo(schema));
}
 
Example #4
Source File: Oracle10ConnectionFactoryTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("oracle jdbc required in classpath")
public void testCreateConnection() throws DatabaseUnitException, SQLException {
    // GIVEN
    final String schema = "foo";

    // WHEN
    final IDatabaseConnection dbConnection = FACTORY.createConnection(connection, schema);

    // THEN
    assertThat(dbConnection, notNullValue());

    final Object typeFactory = dbConnection.getConfig().getProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY);
    assertThat(typeFactory, notNullValue());
    assertThat(typeFactory.getClass(), equalTo(Oracle10DataTypeFactory.class));

    assertThat(dbConnection.getSchema(), equalTo(schema));
}
 
Example #5
Source File: ExportNullPropertiesIt.java    From database-rider with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotExportNullColumnsInJSONDataSet() throws SQLException, DatabaseUnitException{
    DataSetExporter.getInstance().export(new DatabaseConnection(emProvider.connection()), new DataSetExportConfig().
            dataSetFormat(DataSetFormat.JSON).outputFileName("target/userWithNullProperty.json"));
    File jsonDataSet = new File("target/userWithNullProperty.json");
    assertThat(jsonDataSet).exists();
    assertThat(contentOf(jsonDataSet).replaceAll("\r","")).isEqualTo(("{"+NEW_LINE +
            "  \"FOLLOWER\": ["+NEW_LINE +
            "  ],"+NEW_LINE +
            "  \"SEQUENCE\": ["+NEW_LINE +
            "    {"+NEW_LINE +
            "      \"SEQ_NAME\": \"SEQ_GEN\","+NEW_LINE +
            "      \"SEQ_COUNT\": 50"+NEW_LINE +
            "    }"+NEW_LINE +
            "  ],"+NEW_LINE +
            "  \"TWEET\": ["+NEW_LINE +
            "  ],"+NEW_LINE +
            "  \"USER\": ["+NEW_LINE +
            "    {"+NEW_LINE +
            "      \"ID\": 1"+NEW_LINE +
            "    }"+NEW_LINE +
            "  ]"+NEW_LINE +
            "}").replaceAll("\r",""));

}
 
Example #6
Source File: RoutingDatabaseOnlyWithHintForDMLTest.java    From sharding-jdbc-1.5.1 with Apache License 2.0 6 votes vote down vote up
@Test
public void assertInsertWithAllPlaceholders() throws SQLException, DatabaseUnitException {
    for (Map.Entry<DatabaseType, ShardingDataSource> each : shardingDataSources.entrySet()) {
        for (int i = 1; i <= 10; i++) {
            try (DynamicShardingValueHelper helper = new DynamicDatabaseShardingValueHelper(i);
                 Connection connection = each.getValue().getConnection();
                 PreparedStatement preparedStatement = connection.prepareStatement(DatabaseTestSQL.INSERT_ORDER_WITH_ALL_PLACEHOLDERS_SQL)) {
                preparedStatement.setInt(1, i);
                preparedStatement.setInt(2, i);
                preparedStatement.setString(3, "insert");
                preparedStatement.executeUpdate();
            }
        }
        assertDataSet(each.getValue().getConnection(), each.getKey(), "insert", "insert");
    }
}
 
Example #7
Source File: ShardingDatabaseOnlyWithHintForDMLTest.java    From sharding-jdbc-1.5.1 with Apache License 2.0 6 votes vote down vote up
@Test
public void assertInsertWithAllPlaceholders() throws SQLException, DatabaseUnitException {
    for (Map.Entry<DatabaseType, ShardingDataSource> each : shardingDataSources.entrySet()) {
        for (int i = 1; i <= 10; i++) {
            try (DynamicShardingValueHelper helper = new DynamicShardingValueHelper(i, i);
                 Connection connection = each.getValue().getConnection()) {
                PreparedStatement preparedStatement = connection.prepareStatement(DatabaseTestSQL.INSERT_ORDER_WITH_ALL_PLACEHOLDERS_SQL);
                preparedStatement.setInt(1, i);
                preparedStatement.setInt(2, i);
                preparedStatement.setString(3, "insert");
                preparedStatement.executeUpdate();
            }
        }
        assertDataSet(each.getValue().getConnection(), each.getKey(), "insert", "insert");
    }
}
 
Example #8
Source File: PostgresqlConnectionFactoryTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateConnection() throws DatabaseUnitException {
    // GIVEN
    final String schema = "foo";

    // WHEN
    final IDatabaseConnection dbConnection = FACTORY.createConnection(connection, schema);

    // THEN
    assertThat(dbConnection, notNullValue());

    final Object typeFactory = dbConnection.getConfig().getProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY);
    assertThat(typeFactory, notNullValue());
    assertThat(typeFactory.getClass(), not(equalTo(DefaultDataTypeFactory.class)));

    assertThat(dbConnection.getSchema(), equalTo(schema));
}
 
Example #9
Source File: HsqldbConnectionFactoryTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateConnection() throws DatabaseUnitException {
    // GIVEN
    final String schema = "foo";

    // WHEN
    final IDatabaseConnection dbConnection = FACTORY.createConnection(connection, schema);

    // THEN
    assertThat(dbConnection, notNullValue());

    final Object typeFactory = dbConnection.getConfig().getProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY);
    assertThat(typeFactory, notNullValue());
    assertThat(typeFactory.getClass(), equalTo(HsqldbDataTypeFactory.class));

    assertThat(dbConnection.getSchema(), equalTo(schema));
}
 
Example #10
Source File: SqlDbFeatureExecutor.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Override
protected DbFeature<IDatabaseConnection> createVerifyDataAfterFeature(final ExpectedDataSets expectedDataSets) {
    return (final IDatabaseConnection connection) -> {
        try {
            final IDataSet currentDataSet = connection.createDataSet();
            final IDataSet expectedDataSet = mergeDataSets(loadDataSets(Arrays.asList(expectedDataSets.value())));

            final DataSetComparator dataSetComparator = new DataSetComparator(expectedDataSets.orderBy(),
                    expectedDataSets.excludeColumns(), expectedDataSets.strict(), getColumnFilter(expectedDataSets));

            final AssertionErrorCollector errorCollector = new AssertionErrorCollector();
            dataSetComparator.compare(currentDataSet, expectedDataSet, errorCollector);

            errorCollector.report();
        } catch (final SQLException | DatabaseUnitException e) {
            throw new DbFeatureException("Could not execute DB contents verification feature", e);
        }
    };
}
 
Example #11
Source File: MsSqlConnectionFactoryTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateConnection() throws DatabaseUnitException {
    // GIVEN
    final String schema = "foo";

    // WHEN
    final IDatabaseConnection dbConnection = FACTORY.createConnection(connection, schema);

    // THEN
    assertThat(dbConnection, notNullValue());

    final Object typeFactory = dbConnection.getConfig().getProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY);
    assertThat(typeFactory, notNullValue());
    assertThat(typeFactory.getClass(), equalTo(MsSqlDataTypeFactory.class));

    assertThat(dbConnection.getSchema(), equalTo(schema));
}
 
Example #12
Source File: UserDaoTest.java    From wetech-cms with MIT License 6 votes vote down vote up
@Test
public void testFindSQLByArgsAndAlias() throws DatabaseUnitException, SQLException {
	IDataSet ds = createDateSet("t_user");
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds);
	SystemContext.removeOrder();
	SystemContext.removeSort();
	SystemContext.setPageSize(3);
	SystemContext.setPageOffset(0);
	Map<String,Object> alias = new HashMap<String,Object>();
	alias.put("ids", Arrays.asList(1,2,4,5,6,7,8,10));
	Pager<User> expected = userDao.findUserBySql("select * from t_user where id>=? and id<=? and id in (:ids)", new Object[]{1,10},alias,User.class,true);
	List<User> actuals = Arrays.asList(new User(1,"admin1"),new User(2,"admin2"),new User(4,"admin4"));
	assertNotNull(expected);
	assertTrue(expected.getTotal()==8);
	assertTrue(expected.getOffset()==0);
	assertTrue(expected.getSize()==3);
	EntitiesHelper.assertUsers(expected.getDatas(), actuals);
}
 
Example #13
Source File: DBUnitUtil.java    From sharding-jdbc-1.5.1 with Apache License 2.0 6 votes vote down vote up
public static IDatabaseConnection getConnection(final DataBaseEnvironment dbEnv, final Connection connection) throws DatabaseUnitException {
    switch (dbEnv.getDatabaseType()) {
        case H2:
            return new H2Connection(connection, "PUBLIC");
        case MySQL:
            return new MySqlConnection(connection, null);
        case PostgreSQL:
            DatabaseConnection databaseConnection = new DatabaseConnection(connection);
            databaseConnection.getConfig().setProperty("http://www.dbunit.org/properties/datatypeFactory", new PostgresqlDataTypeFactory());
            return databaseConnection;
        case Oracle:
            return new OracleConnection(connection, "JDBC");
        case SQLServer:
            return new MsSqlConnection(connection);
        default:
            throw new UnsupportedOperationException(dbEnv.getDatabaseType().name());
    }
}
 
Example #14
Source File: UserDaoTest.java    From wetech-cms with MIT License 6 votes vote down vote up
@Test
public void testFindSQLByArgs() throws DatabaseUnitException, SQLException {
	IDataSet ds = createDateSet("t_user");
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds);
	SystemContext.setOrder("desc");
	SystemContext.setSort("id");
	SystemContext.setPageSize(3);
	SystemContext.setPageOffset(0);
	Pager<User> expected = userDao.findUserBySql("select * from t_user where id>=? and id<=?", new Object[]{1,10},User.class,true);
	List<User> actuals = Arrays.asList(new User(10,"admin10"),new User(9,"admin9"),new User(8,"admin8"));
	assertNotNull(expected);
	assertTrue(expected.getTotal()==10);
	assertTrue(expected.getOffset()==0);
	assertTrue(expected.getSize()==3);
	EntitiesHelper.assertUsers(expected.getDatas(), actuals);
}
 
Example #15
Source File: ChannelDaoTest.java    From wetech-cms with MIT License 5 votes vote down vote up
@After
public void tearDown() throws DatabaseUnitException, SQLException, IOException {
	SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
	Session s = holder.getSession(); 
	s.flush();
	TransactionSynchronizationManager.unbindResource(sessionFactory);
	this.resumeTable();
}
 
Example #16
Source File: ChannelDaoTest.java    From wetech-cms with MIT License 5 votes vote down vote up
@Before
public void setUp() throws SQLException, IOException, DatabaseUnitException {
	//此时最好不要使用Spring的Transactional来管理,因为dbunit是通过jdbc来处理connection,再使用spring在一些编辑操作中会造成事务shisu
	Session s = sessionFactory.openSession();
	TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));
	this.backupAllTable();
	IDataSet ds = createDateSet("topic");
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds);
}
 
Example #17
Source File: RoleDaoTest.java    From wetech-cms with MIT License 5 votes vote down vote up
@After
public void tearDown() throws DatabaseUnitException, SQLException, IOException {
	SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
	Session s = holder.getSession();
	s.flush();
	TransactionSynchronizationManager.unbindResource(sessionFactory);
	this.resumeTable();
}
 
Example #18
Source File: UserDaoTest.java    From wetech-cms with MIT License 5 votes vote down vote up
@Test
public void testAddUserRole() throws DatabaseUnitException, SQLException {
	Role role = roleDao.load(1);
	User user = userDao.load(1);
	userDao.addUserRole(user, role);
	UserRole ur = userDao.loadUserRole(1, 1);
	assertNotNull(ur);
	assertEquals(ur.getRole().getId(), 1);
	assertEquals(ur.getUser().getId(), 1);
}
 
Example #19
Source File: DataSetComparator.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void shouldBeEmpty(final IDataSet dataSet, final AssertionErrorCollector errorCollector) throws DatabaseUnitException {
    for (final String tableName : dataSet.getTableNames()) {
        final int rowCount = dataSet.getTable(tableName).getRowCount();
        if (rowCount != 0) {
            errorCollector.collect(tableName + " was expected to be empty, but has <" + rowCount + "> entries.");
        }
    }
}
 
Example #20
Source File: Oracle10ConnectionFactory.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Override
public IDatabaseConnection createConnection(final Connection connection, final String schema) throws DatabaseUnitException {
    final DatabaseConnection dbUnitConnection = new DatabaseConnection(connection, schema);

    dbUnitConnection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new Oracle10DataTypeFactory());

    return dbUnitConnection;
}
 
Example #21
Source File: ExportSomeNullPropertiesIt.java    From database-rider with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotExportNullColumnsInJSONDataSet() throws SQLException, DatabaseUnitException {
  DataSetExporter.getInstance().export(new DatabaseConnection(emProvider.connection()), new DataSetExportConfig().
    dataSetFormat(DataSetFormat.JSON).outputFileName("target/userWithNullProperty.json"));
  File jsonDataSet = new File("target/userWithNullProperty.json");
  assertThat(jsonDataSet).exists();
  assertThat(contentOf(jsonDataSet).replaceAll("\r", "")).isEqualTo(("{" + NEW_LINE +
    "  \"FOLLOWER\": [" + NEW_LINE +
    "  ]," + NEW_LINE +
    "  \"SEQUENCE\": [" + NEW_LINE +
    "    {" + NEW_LINE +
    "      \"SEQ_NAME\": \"SEQ_GEN\"," + NEW_LINE +
    "      \"SEQ_COUNT\": 50" + NEW_LINE +
    "    }" + NEW_LINE +
    "  ]," + NEW_LINE +
    "  \"TWEET\": [" + NEW_LINE +
    "    {" + NEW_LINE +
    "      \"ID\": \"1\"," + NEW_LINE +
    "      \"CONTENT\": \"tweet_content\"," + NEW_LINE +
    "      \"LIKES\": 3" + NEW_LINE +
    "    }" + NEW_LINE +
    "  ]," + NEW_LINE +
    "  \"USER\": [" + NEW_LINE +
    "    {" + NEW_LINE +
    "      \"ID\": 1" + NEW_LINE +
    "    }" + NEW_LINE +
    "  ]" + NEW_LINE +
    "}").replaceAll("\r", ""));

}
 
Example #22
Source File: DataSetExecutorIt.java    From database-rider with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void shouldThrowAnExceptionIfExpectedDataSetHasBothOrderByAndRegex() throws DatabaseUnitException {
    DataSetConfig DataSetConfig = new DataSetConfig("datasets/yml/users.yml");
    executor.createDataSet(DataSetConfig);
    DataSetConfig ExpectedDataSetConfig = new DataSetConfig("datasets/yml/expectedUsersRegex.yml");
    executor.compareCurrentDataSetWith(ExpectedDataSetConfig, null, null, new String[] {"name"});
}
 
Example #23
Source File: RoleDaoTest.java    From wetech-cms with MIT License 5 votes vote down vote up
@Before
public void setUp() throws SQLException, IOException, DatabaseUnitException {
	Session s = sessionFactory.openSession();
	TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));
	this.backupAllTable();
	IDataSet ds = createDateSet("t_user");
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
}
 
Example #24
Source File: RiderRunner.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private void performDataSetComparison(RiderTestContext riderTestContext) throws DatabaseUnitException {
    ExpectedDataSet expectedDataSet = riderTestContext.getAnnotation(ExpectedDataSet.class);

    if (expectedDataSet != null) {
        riderTestContext.getDataSetExecutor()
                .compareCurrentDataSetWith(new DataSetConfig(expectedDataSet.value())
                                .disableConstraints(true).datasetProvider(expectedDataSet.provider()),
                        expectedDataSet.ignoreCols(),
                        expectedDataSet.replacers(),
                        expectedDataSet.orderBy(),
                        expectedDataSet.compareOperation());
    }
}
 
Example #25
Source File: RiderRunner.java    From database-rider with Apache License 2.0 5 votes vote down vote up
public void runAfterTest(RiderTestContext riderTestContext) throws SQLException, DatabaseUnitException {
    DataSet dataSet = riderTestContext.getAnnotation(DataSet.class);
    if (dataSet != null) {
        DataSetConfig dataSetConfig = new DataSetConfig().from(dataSet);

        if (dataSetConfig.isTransactional()) {
            riderTestContext.commit();
        }
    }
    performDataSetComparison(riderTestContext);
}
 
Example #26
Source File: RiderDataSource.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private void initDBUnitConnection() throws SQLException {
    try {
        dbUnitConnection = new DatabaseConnection(getConnection(), dbUnitConfig.getSchema());
        configDatabaseProperties();
    } catch (DatabaseUnitException e) {
        throw new SQLException(e);
    }
}
 
Example #27
Source File: UserDaoTest.java    From wetech-cms with MIT License 5 votes vote down vote up
@Test
public void testListSQLByArgs() throws DatabaseUnitException, SQLException {
	IDataSet ds = createDateSet("t_user");
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds);
	SystemContext.setOrder("desc");
	SystemContext.setSort("id");
	List<User> expected = userDao.listUserBySql("select * from t_user where id>? and id<?", new Object[]{1,4},User.class,true);
	List<User> actuals = Arrays.asList(new User(3,"admin3"),new User(2,"admin2"));
	assertNotNull(expected);
	assertTrue(expected.size()==2);
	EntitiesHelper.assertUsers(expected, actuals);
}
 
Example #28
Source File: UserDaoTest.java    From wetech-cms with MIT License 5 votes vote down vote up
@Test
public void testListByArgsAndAlias() throws DatabaseUnitException, SQLException {
	IDataSet ds = createDateSet("t_user");
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds);
	SystemContext.setOrder("asc");
	SystemContext.setSort("id");
	Map<String,Object> alias = new HashMap<String,Object>();
	alias.put("ids", Arrays.asList(1,2,3,5,6,7,8,9,10));
	List<User> expected = userDao.list("from User where id>? and id<? and id in(:ids)", new Object[]{1,5},alias);
	List<User> actuals = Arrays.asList(new User(2,"admin2"),new User(3,"admin3"));
	assertNotNull(expected);
	assertTrue(expected.size()==2);
	EntitiesHelper.assertUsers(expected, actuals);
}
 
Example #29
Source File: UserDaoTest.java    From wetech-cms with MIT License 5 votes vote down vote up
@Test
public void testDeleteUserGroups() throws DatabaseUnitException, SQLException {
	int uid = 2;
	userDao.deleteUserGroups(uid);
	List<Group> ugs = userDao.listUserGroups(uid);
	assertTrue(ugs.size()<=0);
}
 
Example #30
Source File: DataSetExecutorImpl.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private IDataSet performSequenceFiltering(DataSetConfig dataSet, IDataSet target)
        throws DatabaseUnitException, SQLException {
    if (dataSet.isUseSequenceFiltering()) {
        ITableFilter filteredTable = new RiderSequenceFilter(getRiderDataSource().getDBUnitConnection(),
                target.getTableNames(), dbUnitConfig);
        target = new FilteredDataSet(filteredTable, target);
    }
    return target;
}