我试图用dbUnit编写一个集成测试,用于MySQL中一个包含autoincrement
列的表。
集成测试如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={
JdbcRepositoryConfiguration.class,
DbUnitConnectionConfiguration.class
})
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
DbUnitTestExecutionListener.class
})
@DirtiesContext(classMode=ClassMode.AFTER_CLASS)
@DbUnitConfiguration(databaseConnection="dbUnitConnection")
public class IntegrationTest {
@Autowired private JdbcRepositoryConfiguration configuration;
private Loader loader;
@Before
public void setup() throws JSchException {
loader = new Loader(configuration.jdbcTemplate());
}
@Test
@DatabaseSetup("classpath:dataset.xml")
public void loads() throws Exception {
assertThat(loader.load(), contains("something"));
}
}
对于没有increment
列的表,我有相同的集成测试结构,测试工作正常。
dataset.xml
看起来像是:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<sometable
id="1"
regexp="something"
descr="descr"
/>
</dataset>
调试我可以看到设置数据所采取的操作是删除所有数据并执行插入操作,更具体地说:
插入sometable(id,regexp,descr)值(?,?,?)
我得到的错误是:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'regexp, descr) values (1, 'something', 'descr')' at line 1
为了完整性,DbUnitConfiguration.class
具有以下spring bean设置:
@Bean
public IDatabaseConnection dbUnitConnection() throws SQLException, DatabaseUnitException, JSchException {
Connection dbConn = configuration.jdbcTemplate().getDataSource().getConnection();
IDatabaseConnection connection = new DatabaseConnection(dbConn) {
@Override
public void close() throws SQLException {}
};
DatabaseConfig dbConfig = connection.getConfig();
dbConfig.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
return connection;
}
答案 0 :(得分:0)
结果与自动增量无关。
抛出错误是因为列regexp
是MySQL中的保留字。
要解决此问题,dbUnit设置必须包含以下行:
dbConfig.setProperty(DatabaseConfig.PROPERTY_ESCAPE_PATTERN , "`?`");
现在测试工作正常。