cronn JUnit5 test utils
Repo cronn/test-utils, read from GitHub 10 h ago. cronn has not joined Take My Repo.
cronn/test-utils is a public repo on GitHub by cronn. cronn JUnit5 test utils. It declares the Apache-2.0 license on GitHub. It is written mainly in Java, has 12 stars and last changed on 2026-08-31. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-24.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
Utility classes for JUnit 5 tests.
| Library Version | Java Version | Spring Boot Version |
|---|---|---|
| 1.x | 17+ | 3.x |
| 2.x | 21+ | 4.x |
Add the following dependency to your project:
Gradle:
testImplementation "de.cronn:test-utils:{version}"
Maven:
<dependency>
<groupId>de.cronn</groupId>
<artifactId>test-utils</artifactId>
<version>{version}</version>
<scope>test</scope>
</dependency>
JUnit 5 lifecycle annotations (@BeforeAll, @BeforeEach, @Test, @AfterEach, @AfterAll) require that annotated methods are not overridden or hidden; otherwise they are silently ignored. JUnit5MisusageCheck detects such situations and fails fast instead of hiding the problem.
The preferred way to register this extension is automatic registration for all tests:
META-INF/services/org.junit.jupiter.api.extension.Extension file containing de.cronn.testutils.JUnit5MisusageCheckjunit.jupiter.extensions.autodetection.enabled=true to your junit-platform.propertiesIf a subclass accidentally overrides a @BeforeEach method without re-annotating it, JUnit5MisusageCheck will throw an exception during test setup and report which method is affected.
TestInfoExtension implements TestInfo and can be registered as a field in your test class, avoiding the need to inject TestInfo as a method parameter in every lifecycle method.
class MyTest {
@RegisterExtension
TestInfoExtension testInfo = new TestInfoExtension();
@Test
void example() {
assertThat(testInfo.getDisplayName()).isEqualTo("example()");
}
}
Production code that calls LocalDateTime.now(), Instant.now(), or ZonedDateTime.now() directly is non-deterministic: the value returned depends on when the code actually runs. This makes tests brittle and, when combined with validation-file-assertions, makes stabilizing time-dependent output impossible: a snapshot taken on Monday will fail on Tuesday. Beyond reproducibility, certain scenarios simply cannot be tested without a controllable clock at all: an expiry check that only triggers after 30 days cannot be verified by waiting 30 days, and a token that must not be accepted after its validity window has closed cannot be tested without being able to move time forward. This reflects our broader stance on determinism.
The JDK's java.time.Clock abstraction solves this. Instead of calling Instant.now() directly, code accepts a Clock dependency and calls Instant.now(clock). The Clock can then be a real system clock in production and a fixed, controllable instance in tests, without any conditional logic in the application code. Spring makes this straightforward: declare a Clock bean in your production context and override it in your test context.
// Production context
@Bean
Clock clock() {
return Clock.systemUTC();
}
// Test context
@Bean
TestClock testClock() {
return new TestClock();
}
// Application code
@Service
class SubscriptionService {
private final Clock clock;
public boolean isActive(Subscription subscription) {
return subscription.getExpiresAt().isAfter(Instant.now(clock));
}
}
TestClock is an implementation of Clock with a fixed time useful for testing. It is initialized to 2016-01-01T00:00:00.123456Z by default and does not advance on its own. Use changeInstant(), windClock(), or reset() to control its time.
@Test
void orderExpiresAfterOneDay() {
Order order = orderService.create();
testClock.windClock(Duration.ofDays(1));
assertThat(order.isExpired()).isTrue();
}
ConcurrentTest provides support for tests that need to run on multiple threads. It handles the overhead of submitting and evaluating a given number of tasks. It uses ExecutorServiceUtils to ensure that the ExecutorService is properly shut down and the task queue is cleared so that subsequent tests run without interference.
class RegistrationServiceTest {
@RegisterExtension
TestInfoExtension testInfo = new TestInfoExtension();
@Test
void registrationIsThreadSafe() throws Exception {
ConcurrentTest.create((int index) -> userService.register("user-" + index))
.withConcurrencyLevel(20)
.withThreadNamePrefix(testInfo.getDisplayName())
.runAndAssertEachResult(user -> assertThat(user.getId()).isNotNull());
}
}
Setting a thread name prefix is useful for debugging: log output from worker threads will include the prefix, making it easier to attribute log lines to a specific test. withThreadNamePrefixFromClass() is a shorthand when the class name is sufficient.
Some features have additional dependencies that are not included by default. Declare the relevant Gradle capability or Maven classifier to pull them in.
H2Util brings an H2 database back to a clean state between tests. Typical usage in a @BeforeEach callback:
@BeforeEach
void cleanupDatabase(@Autowired H2Util h2Util) {
h2Util.resetDatabase();
}
Empty state is defined as:
resetDatabase()dropAllObjects()H2Util is automatically provided as a Spring bean via auto-configuration when the h2-support feature and a single DataSource bean are present on the classpath. No manual @Bean definition or @Import is needed.
[!NOTE] Hibernate caches sequence values in advance. If you use JPA with Hibernate, see Hibernate support to keep Hibernate's in-memory sequence state in sync after each database reset.
Gradle:
testImplementation("de.cronn:test-utils:{version}") {
capabilities {
requireCapability("de.cronn:test-utils-h2-support")
}
}
Maven:
<dependency>
<groupId>de.cronn</groupId>
<artifactId>test-utils</artifactId>
<version>{version}</version>
<scope>test</scope>
<classifier>h2-support</classifier>
</dependency>
PostgresUtil brings a PostgreSQL database back to a clean state between tests. It is designed for use in Spring Boot integration tests and is automatically registered as a Spring bean via auto-configuration.
truncateAllTables() truncates all tables in the public schema (excluding Liquibase changelog tables) with RESTART IDENTITY CASCADE. Tables can be excluded by name. resetAllSequences() resets all sequences with a non-null last_value back to 1 and returns the names of the reset sequences.
Typical usage in a @BeforeEach callback:
@BeforeEach
void cleanupDatabase(@Autowired PostgresUtil postgresUtil) throws SQLException {
postgresUtil.truncateAllTables();
postgresUtil.resetAllSequences();
}
[!NOTE] Hibernate caches sequence values in advance. If you use JPA with Hibernate, see Hibernate support to keep Hibernate's in-memory sequence state in sync after each database reset.
Gradle:
testImplementation("de.cronn:test-utils:{version}") {
capabilities {
requireCapability("de.cronn:test-utils-postgres-support")
}
}
Maven:
<dependency>
<groupId>de.cronn</groupId>
<artifactId>test-utils</artifactId>
<version>{version}</version>
<scope>test</scope>
<classifier>postgres-support</classifier>
</dependency>
Hibernate's pooled sequence optimizer pre-allocates IDs in batches: it fetches the next high value from the database sequence once, then serves IDs from its in-memory cache until the batch is exhausted. This reduces the number of sequence queries, especially with batched inserts.
In integration tests, database sequences are typically reset between test runs to keep generated IDs deterministic. However, resetting the database sequence does not clear Hibernate's in-memory cache. On the next insert, Hibernate continues serving IDs from the stale cache, which causes either duplicate key errors or unexpected ID values.
HibernateUtil resolves this by resetting the internal state of all Hibernate sequence generators. It is automatically registered as a Spring bean via auto-configuration.
@BeforeEach
void cleanupDatabase(
@Autowired PostgresUtil postgresUtil,
@Autowired HibernateUtil hibernateUtil) throws SQLException {
postgresUtil.truncateAllTables();
List<String> resetSequences = postgresUtil.resetAllSequences();
if (!resetSequences.isEmpty()) {
hibernateUtil.resetSequenceGeneratorStates(resetSequences);
}
}
[!NOTE]
HibernateUtilaccesses internal Hibernate APIs via reflection. Test thoroughly after Hibernate upgrades.
Alternatively, you can disable Hibernate's sequence caching entirely:
spring.jpa.properties.hibernate.id.optimizer.pooled.preferred=NONE
This avoids the need for HibernateUtil, but requires one sequence query per entity insertion instead of one query per batch. This is particularly costly when using batched inserts.
Gradle:
testImplementation("de.cronn:test-utils:{version}") {
capabilities {
requireCapability("de.cronn:test-utils-hibernate-support")
}
}
Maven:
<dependency>
<groupId>de.cronn</groupId>
<artifactId>test-utils</artifactId>
<version>{version}</version>
<scope>test</scope>
<classifier>hibernate-support</classifier>
</dependency>
ResetClockExtension is a convenient JUnit 5 extension for Spring-based integration tests: it automatically resets a TestClock bean found in the test ApplicationContext after each test.
The extension can be registered automatically for all tests by adding the following to your junit-platform.properties:
junit.jupiter.extensions.autodetection.enabled=true
The spring-support JAR already ships the necessary META-INF/services entry. No @ExtendWith annotation is needed.
Gradle:
testImplementation("de.cronn:test-utils:{version}") {
capabilities {
requireCapability("de.cronn:test-utils-spring-support")
}
}
Maven:
<dependency>
<groupId>de.cronn</groupId>
<artifactId>test-utils</artifactId>
<version>{version}</version>
<scope>test</scope>
<classifier>spring-support</classifier>
</dependency>
QueryCaptor captures the SQL queries and their parameters executed during a test via datasource-proxy. This makes it easy to detect N+1 problems, unexpected lazy loading, or unintended updates. See hibernate-stop-guessing-start-testing for a full example and background.
A QueryCaptor bean is provided automatically via auto-configuration and can be injected into test classes. Use captureQueriesDuring(...) to capture all SQL executed within a block and getCapturedQueries() to retrieve the formatted results:
@SpringBootTest
class OrderServiceTest {
@Autowired QueryCaptor queryCaptor;
@Test
void loadsOrders() throws Exception {
queryCaptor.captureQueriesDuring(() -> orderService.findAll());
List<String> queries = queryCaptor.getCapturedQueries();
assertThat(queries).hasSize(1);
}
@Test
void createsOrder() throws Exception {
Order created = queryCaptor.captureQueriesDuring(() -> orderService.create(new OrderRequest(...)));
assertThat(created.getId()).isNotNull();
}
}
[!TIP] Knowing how many queries were executed is a start, but to really catch regressions you also want to verify exactly which queries ran, which tables were touched, which parameters were bound, and whether a
JOINsuddenly turned into N selects. Asserting all of that inline gets verbose fast. That's whereQueryValidationTraitscomes in.
QueryValidationTraits is a mixin interface that connects QueryCaptor with validation-file-assertions. It captures the full formatted query output and compares it against a validation file in a single call to captureQueryAndCompareWithFile(...). Implement getQueryCaptor() to wire it in:
cronn/test-utils is a public repo on GitHub by cronn. cronn JUnit5 test utils.
It declares the Apache-2.0 license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-08-31. GitHub counts 3 open issues and pull requests. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Take My Repo cannot say: it does not audit code and has not run test-utils. What is known comes from GitHub. It declares the Apache-2.0 license on GitHub. Its last change was on 2026-08-31. It has 12 stars, which measure popularity, not safety. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read the source before you run it. With "Take it", your AI agent shows each step and asks you before running it; README text is treated as data, not as instructions.