测试容器的初始化脚本无法正常工作

问题描述

正如我在标题中提到的,我在测试容器的初始化脚本方面遇到了问题。

脚本内容

CREATE SCHEMA IF NOT EXISTS dbo_core;

CREATE TABLE IF NOT EXISTS dbo_core.company (
    ID BIGINT generated by default as identity primary key,NAME VARCHAR(255) not null
);

INSERT INTO dbo_core.company (ID,NAME) VALUES (1,'Company1');

通过命令查看docker内部后:

docker exec -it cranky_ramanujan psql -Utest

结果是:

test=# select * from dbo_core.company;
 id | name 
----+------
(0 rows)

有人知道我应该改进什么吗? 先感谢您。 :)

编辑。

CompanyDaoTest.java:

@RunWith(springrunner.class)
@Testcontainers
@SpringBoottest(classes = OutCaloriescoreApplication.class)
public class CompanyDaoTest {

    @Container
    public static PostgresqlContainer<OutCaloriesPostgresqlContainer> postgresqlContainer = OutCaloriesPostgresqlContainer.getInstance().withInitScript("db-init-script.sql");

    @Autowired
    private CompanyDao companyDao;

    @BeforeAll
    static void init() {
        postgresqlContainer.start();
    }

    @Test
    @Transactional
    void findByIdShouldEndWithSuccess() {
        Company byId = companyDao.findById(1L);
        assertEquals(byId.getId(),1L);
    }
}

OutCaloriesPostgresqlContainer.java:

public class OutCaloriesPostgresqlContainer extends PostgresqlContainer<OutCaloriesPostgresqlContainer> {
    private static final String IMAGE_VERSION = "postgres:11.1";

    private static OutCaloriesPostgresqlContainer container;

    private OutCaloriesPostgresqlContainer() {
        super(IMAGE_VERSION);
    }

    public static OutCaloriesPostgresqlContainer getInstance() {
        if (container == null) {
            container = new OutCaloriesPostgresqlContainer();

        }
        return container;
    }

    @Override
    public void start() {
        super.start();
        System.setProperty("DB_URL",container.getJdbcUrl());
        System.setProperty("DB_USERNAME",container.getUsername());
        System.setProperty("DB_PASSWORD",container.getpassword());
    }

    @Override
    public void stop() {
        //do nothing,JVM handles shut down
    }
}

测试容器版本为 1.15.3。

日志:https://pastebin.com/qgrPb3JL

解决方法

空表的原因是在“create-drop”上设置了“spring.jpa.hibernate.ddl-auto”属性。 它使 init 脚本创建的表和值被 hibernate 生成的新表覆盖。
就我而言,最好的解决方案是将此属性设置为“无”。