如何配置我的Spring Boot应用程序,以便在运行单元测试时,它将使用内存数据库,如H2/HSQL,但是当我运行Spring Boot应用程序时,它将使用生产数据库[Postgre/MySQL]?
spring spring-test spring-data spring-test-dbunit spring-boot
据我所知,TestExecutionListeners就像@BeforeClassJUnit中的方法一样.我不明白的是为什么我需要使用DependencyInjectionTestExecutionListener,TransactionalTestExecutionListener而DirtiesContextTestExecutionListener使用DbUnitTestExecutionListener.
通常没有DbUnit,我可以创建并填充数据库.为什么我突然需要使用这些监听器CRUD为我的数据库做一些事情?
我正在使用spring-test-dbunit,我在单元测试中收到一条警告:
码:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/context.xml"})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class })
public class TestDB {
    @Autowired 
    private ICourseService courseService;
    @Test
    @DatabaseSetup("sampleData.xml")
    public void testFind() throws Exception {
        List<Course> courseList = this.courseService.getAllCourses();
        assertEquals(1, courseList.size());
        assertEquals("A001", courseList.get(0).getCourseNumber());
    }
}
警告:
1093 [main] WARN org.dbunit.dataset.AbstractTableMetaData - 发现潜在问题:配置的数据类型factory'class org.dbunit.dataset.datatype.DefaultDataTypeFactory'可能导致当前数据库'MySQL'出现问题(例如某些数据类型可能不会得到适当支持).在极少数情况下,您可能会看到此消息,因为受支持的数据库产品列表不完整(list = [derby]).如果是这样,请通过论坛请求java级更新.如果您使用自己的IDataTypeFactory扩展DefaultDataTypeFactory,请确保覆盖getValidDbProducts()以指定支持的数据库产品.
当我使用没有spring-test-dbunit的DBunit时,问题可以解决如下:
  Connection jdbcConnection = DriverManager.getConnection( "jdbc:mysql://localhost/test", "root", "root");
        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
        connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
        connection.getConfig().setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, new MySqlMetadataHandler());
我不知道如何在spring-test-dbunit中解决这个问题.请帮忙.
我通过java配置配置了我的测试环境.在我的测试中,我需要一些数据来预先运行它,但是当我使用@DatabaseSetup注释运行测试时,我总是得到错误
Unable to load dataset from "personTestData.xml" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoader
该文件位于src/test/resources/personTestData.xml.出于好奇,我将文件移动到测试本身所在的同一个包中,仍然是同样的错误.
我花了无数个小时在网上搜索错误,直到现在都没有解决方案.
UPDATE
我使用的组件和版本:
junit: 4.12
hamcrest: 1.3
springtestdbunit: 1.2.1
dbunit: 2.5.0
bonecp: 0.8.0
hsqldb: 1.8.0.10
我的xml
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <person id="uuid'da578845-356c-4c99-9bda-c288c88e7b55" 
            dateCreated="2015-03-24 10:54:00"
            isEnabled="1"
            city="Graz"
            displayName="42"
            email="dent@example.com"
            firstname="Arthur"
            lastname="Dent"
            phone="01123456"
            street="Waßkannergasse 16"
            web="www.vdsoft.at"
            zip="1010"/>
    <person id="uuid'5aaae7dd-b84f-463e-a534-e7b2bc54752a" 
            dateCreated="2015-03-24 10:54:10"
            isEnabled="1"
            city="Graz"
            displayName="Towel"
            email="prefect@example.com"
            firstname="Ford"
            lastname="Prefect"
            phone="01123856"
            street="Waßkannergasse 45"
            web="www.vdsoft.at"
            zip="1010"/>
    <person id="uuid'b770b982-3a59-4292-9fd8-715afa2c1bef" 
            dateCreated="2015-03-24 10:54:20"
            isEnabled="1"
            city="Graz"
            displayName="Lemon"
            email="beeblebrox@example.com"
            firstname="Zaphod"
            lastname="Beeblebrox"
            phone="01125456"
            street="Waßkannergasse 20"
            web="www.vdsoft.at"
            zip="1010"/> …在学习了SpringBoot之后,我想进一步使用(DBUnit和SpringTestDBUnit)来处理集成测试.在整个过程中,一切进展顺利,直到我遇到数据集上布尔数据类型列的设置值.(数据集的内容如下)
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <Client code="0001" name="client_one" />
    <Client code="0002" name="client_two" />
    <Client code="0003" name="client_three" active="false" />
    <Client code="0004" name="client_four" />
</dataset>
将active="false"属性添加到客户端记录[code = 0003],我的集成测试失败并向我显示此消息Exception processing table name='Client',导致客户端记录[code = 0001]违反了活动非空列约束.
通过在所有记录(有点偏离规范)上提供活动列的值来修复错误(在分支DBUnit_For_Boolean_Columns_Attempt_One上)之后,它起作用了.但是我的目标能够使用上面编写的数据集成功运行集成测试.
问题是如何使用上面的数据集成功进行集成测试?截至目前,我很难实现解决方案,所以我创建了一个Bitbucket存储库供您查看和帮助.
更新日志
2015/02/04变更
我已经阅读了许多有关使用Spring进行集成测试的帖子和主题,但是没有什么令人满意或有用的。
我们将Spring 3.2.3与Hibernate,Spring Data和Oracle数据库一起使用。对于测试,我们还使用DbUnit和Spring-test-dbunit。在生产代码中,事务由控制器启动,服务本身对事务一无所知。
所以,这是我的测试:
@ContextConfiguration // ...
@ActiveProfiles // ...
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    ModifiedDbUnitTestExecutionListener.class })
@DbUnitConfiguration(databaseConnection = "oracleConnection")
@DatabaseSetup("/database/snapshot/snapshot.xml")
public class IntegrationTest extends AbstractTransactionalJUnit4SpringContextTests
{
    @Test
    public void sampleTest()
    {
        // transaction is already started
        this.assertThatNewsContains(0);
        News news1 = new News();
        news1.setTitle("Test News 1");
        News savedNews1 = this.newsService.save(news1);
        Assert.assertTrue(savedNews1.getId() > 0);
        News news2 = new News();
        news2.setTitle("Test News 2");
        News savedNews2 = this.newsService.save(news2);
        Assert.assertTrue(savedNews2.getId() > 0);
        News news3 = new News();
        news3.setTitle("Test News 3");
        News savedNews3 = …我想知道使 DbUnit 与 MySQL 的 JSON(B) 类型列一起使用的最佳方法是什么?我们确实到处都有这样的列,每当我尝试通过 XML 文件提供测试数据时,@DatabaseSetup我都会收到 NoSuchColumnException,这会阻止我对处理 JSON 的实体或存储库进行任何合理的集成测试:
org.dbunit.dataset.NoSuchColumnException: assistant_event.AEV_CONTEXT -  (Non-uppercase input column: aev_context) in ColumnNameToIndexes cache map. Note that the map's column names are NOT case sensitive.
我知道这是因为我的AEV_CONTEXT列没有被识别,因为它是一个 JSON 列:
@Type(type = "json")
@Column(name = "aev_context", columnDefinition = "json")
private Context context;
然而,我在尝试解决这个问题时遇到了困难。而且,更奇怪的是,我在这里也找不到这样的解决方法!事实上,我不知道那是属于 Hibernate 还是 DbUnit。
到目前为止真的只有我遇到这个问题吗?任何建议将不胜感激!
哦,如果您想知道,这就是我如何获得 Hibernate 的 JSON 支持:
https://vladmihalcea.com/how-to-map-json-objects-using-generic-hibernate-types/
考虑典型的DBUnit Spring Test(请参阅https://github.com/springtestdbunit/spring-test-dbunit):
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:/META-INF/spring/applicationContext-database.xml",
"classpath:spring-*.xml"
})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class })
@DatabaseSetup("/dbunit/data.xml")
public class UnitTest {
    @Autowired
    private UnitUnderTest uut;
    @Test
    public void shouldInitDB() {
         ...
    }
}
我已经验证的是,并且预计,自动装配将在DatabaseSetup之前发生.这必须发生,因为DBUnit依赖于应用程序上下文来提供配置的数据源.
问题是UnitUnderTest bean有一个@PostConstruct,它从DB加载一些数据但是,由于自动装配发生在DBunit设置之前,因此在这个阶段数据将不可用.
关于如何以干净的方式解决这个问题的任何想法?
@DatabaseSetup使用Spring Test DBUnit 的注释时是否可以设置表模式名称?目前我正在这样使用它:
@DatabaseSetup("user-data.xml")
public class UserMapperTest {
}
user-data.xml:(我也尝试将元素名称设置为 user.system_user 但没有任何运气)
<dataset>
    <system_user
        ...
        />
</dataset>
在这里,我使用名为 user 的模式创建表:
create table "user".system_user (...);
这是我在运行测试时遇到的异常:
org.h2.jdbc.JdbcSQLException: Table "SYSTEM_USER" not found; SQL statement:
delete from SYSTEM_USER [42102-175]
我运行测试时遇到以下错误:
org.dbunit.dataset.NoSuchColumnException: myTable.MYFIELD -  (Non-uppercase input column: myfield) in ColumnNameToIndexes cache map. Note that the map's column names are NOT case sensitive.
    at org.dbunit.dataset.AbstractTableMetaData.getColumnIndex(AbstractTableMetaData.java:117)
我设置了断点org.dbunit.dataset.AbstractTableMetaData#getColumnIndex并发现了以下内容.在IntelliJ Idea中,该方法如下所示:
public int getColumnIndex(String columnName) throws DataSetException 
{
    logger.debug("getColumnIndex(columnName={}) - start", columnName);
    if(this._columnsToIndexes == null) 
    {
        // lazily create the map
        this._columnsToIndexes = createColumnIndexesMap(this.getColumns());
    }
    String columnNameUpperCase = columnName.toUpperCase();
    Integer colIndex = (Integer) this._columnsToIndexes.get(columnNameUpperCase);
    if(colIndex != null) 
    {
        return colIndex.intValue();
    }
    else 
    {
        throw new NoSuchColumnException(this.getTableName(), columnNameUpperCase,
                " (Non-uppercase input column: "+columnName+") in …我正在尝试从 Junit4 迁移到 Junit5,因为我知道我正在使用 Spring Mvc 版本 4.3.5,并且我想知道是否可以通过某种方式使用 dbUnit 来处理我的类存储库
\n我做了研究,Dbunit 的最后一个依赖版本是 2.7.3 使用 Junit4。因此,我需要确认在使用 Junit 5 时无法使用 Dbunit,除非我决定迁移到 Spring 5 或 Spring Boot,因为我发现了一些讨论此问题的文章
\n我的旧版本班级测试的标题通常不需要它来回答我的问题,但由于质量原因我无法在这里发布问题,它是:
\nContextConfiguration\n\n@TestPropertySource(locations = "classpath:environnements.properties")\n@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class,\n        TransactionDbUnitTestExecutionListener.class })\n//TODO ajouter les xml des d\xc3\xa9pendances\n// faire par groupes de dependances dans chaque test ?\n@DatabaseSetup(value = {"/dbunit/RepositoryTyp-setup.xml", "/dbunit/RepositoryPTest-setup.xml"}, type = DatabaseOperation.CLEAN_INSERT)\npublic class PRepositoryTest extends SpringDbBasedTest {\n我试图只删除我使用@DatabaseSetup注释插入的记录.
我的测试看起来像这样:
@Test
@DatabaseSetup("classpath:data-set.xml")
@DatabaseTearDown(value={"classpath:data-set.xml"}, type= DatabaseOperation.DELETE)
public void testSomething() throws Exception {
数据set.xml
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <person id="1" name="Joe"/>
</dataset>
据推测,使用DatabaseOperation.DELETE意味着"删除与数据集中的行匹配的数据库表行".但是当我执行测试时,它会擦除表格中的所有数据.
我认为问题是用于拆卸的xml文件的格式.我尝试使用不同的格式:
首先尝试使用tear-down.xml
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <person id="1"/>
</dataset>
第二次尝试使用tear-down.xml
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <person/>
</dataset>
无论使用何种格式,它总是删除表中的所有数据.我找不到用于拆除的格式的单个例子,而不是简单地列出表名.在大多数示例中,人们似乎都使用相同的xml文件进行设置和拆卸.
但这必须是可能的,不是吗?
我正在尝试使用Spring Test DBUnit来运行集成测试,以检查DAO的服务是否正常运行.对于两个类似的实体,我能够创建运行正常的测试,但是对于这个特定的实体,测试无法正常运行.
测试将被忽略,我将在控制台中看到的唯一例外是:
java.lang.IllegalArgumentException: Unable to load dataset from "data/offline_message.xml" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoader
这是相关文件.XML文件:
<dataset>
    <mp_account id="1" auth_hash="ted.mosby" first_name="Ted" last_name="Mosby" credential="EMAIL" transport_session="someTransportSession"/>
    <mp_account id="2" auth_hash="lily.aldrin" first_name="Lily" last_name="Aldrin" credential="MEH" transport_session="someTransportSession"/>
    <mp_message id="1" recipient_account_id="1" sender_account_id="2"/>
</dataset>
失败的测试类:
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.somecompany.messaging.domain.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Date;
import java.util.List;
@DatabaseSetup("data/message.xml")
public class MessageDaoTest extends AbstractDaoTest<Message> {
    private static final Long ACCOUNT_ID = 1L;
    public static final long DATE_LONG = 1431018764154L;
    private static final Date LAST_UPDATE_TS …dbunit ×10
java ×6
spring ×6
spring-test ×4
junit ×2
testing ×2
dao ×1
junit4 ×1
junit5 ×1
mysql ×1
postgresql ×1
spring-boot ×1
spring-data ×1
testng ×1
transactions ×1