- Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathReactiveTest.java
executable file
·268 lines (231 loc) · 8.55 KB
/
ReactiveTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/* Hibernate, Relational Persistence for Idiomatic Java
*
* SPDX-License-Identifier: Apache-2.0
* Copyright: Red Hat Inc. and Hibernate Authors
*/
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS io.vertx:vertx-pg-client:${vertx.version:4.5.14}
//DEPS com.ongres.scram:client:2.1
//DEPS io.vertx:vertx-db2-client:${vertx.version:4.5.14}
//DEPS io.vertx:vertx-mysql-client:${vertx.version:4.5.14}
//DEPS io.vertx:vertx-unit:${vertx.version:4.5.14}
//DEPS org.hibernate.reactive:hibernate-reactive-core:${hibernate-reactive.version:3.0.0.Beta1}
//DEPS org.assertj:assertj-core:3.26.3
//DEPS junit:junit:4.13.2
//DEPS org.testcontainers:postgresql:1.20.6
//DEPS org.testcontainers:mysql:1.20.6
//DEPS org.testcontainers:db2:1.20.6
//DEPS org.testcontainers:mariadb:1.20.6
//DEPS org.testcontainers:cockroachdb:1.20.6
//
//// Testcontainer needs the JDBC drivers to start the containers
//// Hibernate Reactive doesn't use them
//DEPS org.postgresql:postgresql:42.7.4
//DEPS com.mysql:mysql-connector-j:9.1.0
//DEPS org.mariadb.jdbc:mariadb-java-client:3.5.1
//
importjava.util.function.Supplier;
importjakarta.persistence.Entity;
importjakarta.persistence.Id;
importorg.hibernate.boot.registry.StandardServiceRegistry;
importorg.hibernate.boot.registry.StandardServiceRegistryBuilder;
importorg.hibernate.cfg.Configuration;
importorg.hibernate.reactive.mutiny.Mutiny;
importorg.hibernate.reactive.provider.ReactiveServiceRegistryBuilder;
importorg.hibernate.reactive.provider.Settings;
importorg.junit.After;
importorg.junit.Before;
importorg.junit.BeforeClass;
importorg.junit.Test;
importorg.junit.runner.JUnitCore;
importorg.junit.runner.Result;
importorg.junit.runner.RunWith;
importorg.junit.runner.notification.Failure;
importio.vertx.ext.unit.Async;
importio.vertx.ext.unit.TestContext;
importio.vertx.ext.unit.junit.VertxUnitRunner;
importorg.testcontainers.containers.CockroachContainer;
importorg.testcontainers.containers.Db2Container;
importorg.testcontainers.containers.JdbcDatabaseContainer;
importorg.testcontainers.containers.MariaDBContainer;
importorg.testcontainers.containers.MySQLContainer;
importorg.testcontainers.containers.PostgreSQLContainer;
importstaticorg.assertj.core.api.Assertions.assertThat;
/**
* An example of a JUnit test class for Hibernate Reactive using
* <a hreaf="https://vertx.io/docs/vertx-unit/java/">Vert.x Unit</a> and
* <a hreaf="https://www.testcontainers.org/">Testcontainers</a>
* that you can run using <a hreaf="https://www.jbang.dev/">JBang</a>.
* <p>
* Before running the tests, Testcontainers will start the selected
* Docker image with the required database created.
* </p>
* <p>
* The {@link #DATABASE} constant define which database to use and
* it can be change to any of the values in {@link Database}.
* </p>
* <p>
* Usage example:
* <dl>
* <dt>1. Download JBang</dt>
* <dd>See <a hreaf="https://www.jbang.dev/download">https://www.jbang.dev/download</a></dd>
* <dt>2. Run the test with JBang</dt>
* <dd>
* <pre>jbang ReactiveTest.java</pre>
* </dd>
* <dt>3. (Optional) Edit the file (with IntelliJ IDEA for example):</dt>
* <dd>
* <pre>jbang edit --open=idea SampleIssueTest.java</pre>
* </dd>
* </dl>
* <p/>
* <p>
* Note that in a real case scenario, you would only need the dependencies
* for the database of your choice.
* </p>
*/
@RunWith(VertxUnitRunner.class)
publicclassReactiveTest {
/**
* The database to use for the tests
*/
publicfinalstaticDatabaseDATABASE = Database.POSTGRESQL;
privatestaticJdbcDatabaseContainer<?> container;
privateMutiny.SessionFactorysessionFactory;
@BeforeClass
publicstaticvoidstartContainer() {
container = DATABASE.startContainer();
}
/**
* The {@link Configuration} for the {@link Mutiny.SessionFactory}.
*/
privateConfigurationcreateConfiguration() {
Configurationconfiguration = newConfiguration();
// JDBC url
configuration.setProperty( Settings.URL, container.getJdbcUrl() );
// Credentials
configuration.setProperty( Settings.USER, container.getUsername() );
configuration.setProperty( Settings.PASS, container.getPassword() );
// Schema generation. Supported values are create, drop, create-drop, drop-create, none
configuration.setProperty( Settings.HBM2DDL_AUTO, "create" );
// Register new entity classes here
configuration.addAnnotatedClass( MyEntity.class );
// (Optional) Log the SQL queries
configuration.setProperty( Settings.SHOW_SQL, "true" );
configuration.setProperty( Settings.HIGHLIGHT_SQL, "true" );
configuration.setProperty( Settings.FORMAT_SQL, "true" );
returnconfiguration;
}
/*
* Create a new factory and a new schema before each test (see
* property `hibernate.hbm2ddl.auto`).
* This way each test will start with a clean database.
*
* The drawback is that, in a real case scenario with multiple tests,
* it can slow down the whole test suite considerably. If that happens,
* it's possible to make the session factory static and, if necessary,
* delete the content of the tables manually (without dropping them).
*/
@Before
publicvoidcreateSessionFactory() {
Configurationconfiguration = createConfiguration();
StandardServiceRegistryBuilderbuilder = newReactiveServiceRegistryBuilder()
.applySettings( configuration.getProperties() );
StandardServiceRegistryregistry = builder.build();
sessionFactory = configuration.buildSessionFactory( registry )
.unwrap( Mutiny.SessionFactory.class );
}
@Test
publicvoidtestInsertAndSelect(TestContextcontext) {
// the test will wait until async.complete or context.fail are called
Asyncasync = context.async();
MyEntityentity = newMyEntity( "first entity", 1 );
sessionFactory
// insert the entity in the database
.withTransaction( (session, tx) -> session.persist( entity ) )
.chain( () -> sessionFactory
.withSession( session -> session
// look for the entity by id
.find( MyEntity.class, entity.getId() )
// assert that the returned entity is the right one
.invoke( foundEntity -> assertThat( foundEntity.getName() ).isEqualTo( entity.getName() ) ) ) )
.subscribe()
.with( res -> async.complete(), context::fail );
}
@After
publicvoidcloseFactory() {
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
/**
* Example of a class representing an entity.
* <p>
* If you create new entities, be sure to add them in {@link #createConfiguration()}.
* For example:
* <pre>
* configuration.addAnnotatedClass( MyOtherEntity.class );
* </pre>
*/
@Entity(name = "MyEntity")
publicstaticclassMyEntity {
@Id
publicIntegerid;
publicStringname;
publicMyEntity() {
}
publicMyEntity(Stringname, Integerid) {
this.name = name;
this.id = id;
}
publicIntegergetId() {
returnid;
}
publicStringgetName() {
returnname;
}
@Override
publicStringtoString() {
return"MyEntity"
+ "\n\t id = " + id
+ "\n\t name = " + name;
}
}
/**
* The only purpose of this class is to make it easier to switch among the available databases
* for this unit test.
* <p>
* It's a wrapper around the testcontainers classes.
*/
enumDatabase {
POSTGRESQL( () -> newPostgreSQLContainer( "postgres:17.4" ) ),
MYSQL( () -> newMySQLContainer( "mysql:9.2.0" ) ),
DB2( () -> newDb2Container( "docker.io/icr.io/db2_community/db2:12.1.0.0" ).acceptLicense() ),
MARIADB( () -> newMariaDBContainer( "mariadb:11.7.2" ) ),
COCKROACHDB( () -> newCockroachContainer( "cockroachdb/cockroach:v24.1.15" ) );
privatefinalSupplier<JdbcDatabaseContainer<?>> containerSupplier;
Database(Supplier<JdbcDatabaseContainer<?>> supplier) {
containerSupplier = supplier;
}
publicJdbcDatabaseContainer<?> startContainer() {
JdbcDatabaseContainer<?> jdbcDatabaseContainer = containerSupplier.get();
jdbcDatabaseContainer
.withReuse( true )
.start();
returnjdbcDatabaseContainer;
}
}
// This main class is only for JBang so that it can run the tests with `jbang ReactiveTest`
publicstaticvoidmain(String[] args) {
System.out.println( "Starting the test suite with " + DATABASE );
Resultresult = JUnitCore.runClasses( ReactiveTest.class );
for ( Failurefailure : result.getFailures() ) {
System.out.println();
System.err.println( "Test " + failure.getTestHeader() + " FAILED!" );
System.err.println( "\t" + failure.getTrace() );
}
System.out.println();
System.out.print("Tests result summary: ");
System.out.println( result.wasSuccessful() ? "SUCCESS" : "FAILURE" );
}
}