无法运行使用H2数据库的JPA Repository的JUnit测试 – 为什么没有返回数据?

huangapple go评论74阅读模式
英文:

Unable to run JUnit test of JPA Repository with H2 database - why is no data returned?

问题

更新: 不知何故数据未被插入。已执行删除表和创建表操作,但未插入行。我将data.sql移动到src/test/resources/目录下。

我正在测试使用H2数据库的SpringBoot应用程序。它正在IntelliJ IDE中运行。

当我在IDE中启动SpringBoot应用程序时,我可以在浏览器中查询控制台http://localhost:8080/h2-console。但是,当我停止IDE时,无法访问。application.properties中的数据库URL为spring.datasource.url=jdbc:h2:~/test

我的其他JUnit测试正常运行(使用模拟存储库)。

当我测试存储库时,我运行SpringBoot应用程序以确保数据库存在,但我收到一个长度为零的列表。

@ExtendWith(SpringExtension.class)
@DataJpaTest
class EncouragementRepositoryTest {
    @Autowired
    EncouragementRepository repository;

    @BeforeEach
    void setUp() {
    }

    @Test
    public void find_all() {
        List<Encouragement> list = repository.findAll();
        assertEquals(33, list.size());
    }
}

我不知道为什么它失败并返回长度为零的列表。

因此,我认为可能是数据库没有被填充。

我将数据库URL更改为:

spring.datasource.url=jdbc:h2:~/test;INIT=RUNSCRIPT FROM '~/Documents/Projects/regular-encourager/encourage/src/main/resources/data.sql';

src/main/resources/data.sql中,我包含了以下脚本:

drop table ENCOURAGEMENT if exists;
CREATE TYPE Category AS ENUM('WhoIAmInChrist','Default');
CREATE TYPE Tone AS ENUM('Default', 'Uplifting', 'Urging', 'Warning', 'Soothing', 'Comforting', 'Inspiring', 'Centering', 'Balanced');
CREATE TYPE Topic AS ENUM('Default', 'AcceptedInChrist', 'SignificantInChrist', 'SecureInChrist', 'NoAnxietyInChrist');
CREATE TABLE Encouragement(ID INT PRIMARY KEY, CATEGORY Category, TOPIC Topic, TONE Tone, MESSAGE VARCHAR(512));
INSERT INTO Encouragement VALUES(-1, 'Default', 'Default', 'Default', 'We walk by Faith, not by Sight');
INSERT INTO Encouragement VALUES(0,'WhoIAmInChrist','AcceptedInChrist','Uplifting','John 1:12 I am God\'s child.');
INSERT INTO Encouragement VALUES(1,'WhoIAmInChrist','AcceptedInChrist','Uplifting','John 15:15 As a disciple, I am a friend of Jesus Christ.');
...

这是IDE控制台的输出。

我查看了类似https://stackoverflow.com/q/38022284/398348的SO问题,但它不适用,因为我没有使用事务。

更新:

我尝试在data.sql中添加以下内容:

drop TYPE Category if exists;
drop TYPE Tone if exists;
drop TYPE Topic if exists;

但没有变化。

英文:

Update: somehow the data is not being inserted. the drop table and create table is executed but not the insert rows. I moved data.sql to src/test/resources/


I am testing my SpringBoot application which uses the H2 db.
It is running in IntelliJ IDE.

When I launch the SpringBoot application in the IDE, I can query the console http://localhost:8080/h2-console in the browser. When I stop the IDE, I am unable to.
The DB url in application.properties is spring.datasource.url=jdbc:h2:~/test.

My other JUnit tests are working (mocked repository).

When I test the repository,
I run the SpringBoot application so that the DB is present,
but I get a zero length list back.

@ExtendWith(SpringExtension.class)
@DataJpaTest
class EncouragementRepositoryTest {
@Autowired
EncouragementRepository repository;
    @BeforeEach
    void setUp() {
    }
    @Test
    public void find_all() {
        List&lt;Encouragement&gt; list = repository.findAll();
        assertEquals(33,list.size());
    }
}

I don't know why it is failing and returning zero length list.

So I thought perhaps the DB isn't seeded.

I changed the db url to

spring.datasource.url=jdbc:h2:~/test;INIT=RUNSCRIPT FROM '~/Documents/Projects/regular-encourager/encourage/src/main/resources/data.sql'

In src/main/resources/data.sql I included a script like this:

drop table ENCOURAGEMENT if exists;
CREATE TYPE Category AS ENUM(&#39;WhoIAmInChrist&#39;,&#39;Default&#39;);
CREATE TYPE Tone AS ENUM(&#39;Default&#39;, &#39;Uplifting&#39;, &#39;Urging&#39;, &#39;Warning&#39;, &#39;Soothing&#39;, &#39;Comforting&#39;, &#39;Inspiring&#39;, &#39;Centering&#39;, &#39;Balanced&#39;);
CREATE TYPE Topic AS ENUM(&#39;Default&#39;, &#39;AcceptedInChrist&#39;, &#39;SignificantInChrist&#39;, &#39;SecureInChrist&#39;, &#39;NoAnxietyInChrist&#39;);
CREATE TABLE Encouragement(ID INT PRIMARY KEY, CATEGORY Category, TOPIC Topic, TONE Tone, MESSAGE VARCHAR(512));
INSERT INTO Encouragement VALUES(-1, &#39;Default&#39;, &#39;Default&#39;, &#39;Default&#39;, &#39;We walk by Faith, not by Sight&#39;);
INSERT INTO Encouragement VALUES(0,&#39;WhoIAmInChrist&#39;,&#39;AcceptedInChrist&#39;,&#39;Uplifting&#39;,&#39;John 1:12 I am God&#39;&#39;s child.&#39;);
INSERT INTO Encouragement VALUES(1,&#39;WhoIAmInChrist&#39;,&#39;AcceptedInChrist&#39;,&#39;Uplifting&#39;,&#39;John 15:15 As a disciple, I am a friend of Jesus Christ.&#39;);

.....

Here is the IDE console:

I looked at SO questions like https://stackoverflow.com/q/38022284/398348 but it did not apply as I am not using a transaction.

Update:

I tried adding to data.sql

drop TYPE Category if exists;
drop TYPE Tone if exists;
drop TYPE Topic if exists;

But no change

  .   ____          _            __ _ _
/\\ / ___&#39;_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | &#39;_ | &#39;_| | &#39;_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
&#39;  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::                (v2.7.5)
2023-01-08 10:23:38.296  INFO 16188 --- [           main] c.d.e.data.EncouragementRepositoryTest   : Starting EncouragementRepositoryTest using Java 17.0.4.1 on ME-LAPTOP with PID 16188 (started by MEr in C:\Users\ME\Documents\Projects\regular-encourager\encourage)
2023-01-08 10:23:38.298  INFO 16188 --- [           main] c.d.e.data.EncouragementRepositoryTest   : No active profile set, falling back to 1 default profile: &quot;default&quot;
2023-01-08 10:23:39.132  INFO 16188 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-01-08 10:23:39.230  INFO 16188 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 83 ms. Found 1 JPA repository interfaces.
2023-01-08 10:23:39.396  INFO 16188 --- [           main] beddedDataSourceBeanFactoryPostProcessor : Replacing &#39;dataSource&#39; DataSource bean with embedded version
2023-01-08 10:23:39.748  INFO 16188 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url=&#39;jdbc:h2:mem:879ae9b2-42b9-4672-a7bb-0b4533633f86;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false&#39;, username=&#39;sa&#39;
2023-01-08 10:23:40.301  INFO 16188 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2023-01-08 10:23:40.378  INFO 16188 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.12.Final
2023-01-08 10:23:40.618  INFO 16188 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2023-01-08 10:23:40.762  INFO 16188 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate: drop table if exists encouragement CASCADE 
Hibernate: create table encouragement (id bigint not null, category varchar(255), message varchar(255), tone varchar(255), topic varchar(255), primary key (id))
2023-01-08 10:23:41.508  INFO 16188 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2023-01-08 10:23:41.514  INFO 16188 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit &#39;default&#39;
2023-01-08 10:23:42.066  INFO 16188 --- [           main] c.d.e.data.EncouragementRepositoryTest   : Started EncouragementRepositoryTest in 4.483 seconds (JVM running for 6.372)
2023-01-08 10:23:42.102  INFO 16188 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@748741cb testClass = EncouragementRepositoryTest, testInstance = com.dropaflame.encourage.data.EncouragementRepositoryTest@26df6e3a, testMethod = find_all@EncouragementRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@3e44f2a5 testClass = EncouragementRepositoryTest, locations = &#39;{}&#39;, classes = &#39;{class com.dropaflame.encourage.EncourageApplication}&#39;, contextInitializerClasses = &#39;[]&#39;, activeProfiles = &#39;{}&#39;, propertySourceLocations = &#39;{}&#39;, propertySourceProperties = &#39;{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}&#39;, contextCustomizers = set[[ImportsContextCustomizer@295cf707 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@29215f06, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@6bd61f98, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@5d534f5d, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@6fdbe764, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@879d24c0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@6e6f2380, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], contextLoader = &#39;org.springframework.boot.test.context.SpringBootContextLoader&#39;, parent = [null]], attributes = map[&#39;org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents&#39; -&gt; false]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@733fa95c]; rollback [true]
Hibernate: select encouragem0_.id as id1_0_, encouragem0_.category as category2_0_, encouragem0_.message as message3_0_, encouragem0_.tone as tone4_0_, encouragem0_.topic as topic5_0_ from encouragement encouragem0_
2023-01-08 10:23:42.502  INFO 16188 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@748741cb testClass = EncouragementRepositoryTest, testInstance = com.dropaflame.encourage.data.EncouragementRepositoryTest@26df6e3a, testMethod = find_all@EncouragementRepositoryTest, testException = org.opentest4j.AssertionFailedError: expected: &lt;33&gt; but was: &lt;0&gt;, mergedContextConfiguration = [MergedContextConfiguration@3e44f2a5 testClass = EncouragementRepositoryTest, locations = &#39;{}&#39;, classes = &#39;{class com.dropaflame.encourage.EncourageApplication}&#39;, contextInitializerClasses = &#39;[]&#39;, activeProfiles = &#39;{}&#39;, propertySourceLocations = &#39;{}&#39;, propertySourceProperties = &#39;{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}&#39;, contextCustomizers = set[[ImportsContextCustomizer@295cf707 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@29215f06, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@6bd61f98, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@5d534f5d, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@6fdbe764, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@879d24c0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@6e6f2380, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], contextLoader = &#39;org.springframework.boot.test.context.SpringBootContextLoader&#39;, parent = [null]], attributes = map[&#39;org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents&#39; -&gt; false]]
org.opentest4j.AssertionFailedError: 
Expected :33
Actual   :0
&lt;Click to see difference&gt;

答案1

得分: 1

你曾经尝试将数据文件放在src/test/resources而不是src/main/resources吗?

英文:

Have you ever tried to put the data file in src/test/resources instead of src/main/resources ?

huangapple
  • 本文由 发表于 2023年1月8日 22:34:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定