- 1. Why Sleuth Exists
- 2. Module Layout
- 3. Quick Start
- 4. Annotations
- 5. The Dependency Model
- 6. Lifecycle, Step by Step
- 7. The Event Model
- 8. Sharing State:
TestContext - 9. Concurrency Model
- 10. TestNG Interoperability
- 11. The Maven Surefire Provider
- 12. Architecture Reference
- 13. Worked Examples
- 14. Exception Reference
- 15. Package File Map
- 16. License
Sleuth is a lightweight Java test framework — and a Maven Surefire provider — built around first-class dependencies between test suites and between tests. It is designed for test suites whose correctness is genuinely ordered (integration tests, end-to-end flows, staged pipelines) while still permitting aggressive parallelism wherever the graph allows it. Sleuth understands its own annotations natively and can transparently execute unmodified TestNG test classes.
Most JVM test frameworks are built on an assumption that tests are independent. JUnit deliberately randomizes order to keep authors honest; JUnit 5’s parallel executor has no notion of "this test must not start until that other test succeeded." TestNG does express dependsOnMethods and dependsOnGroups, but its configuration surface — XML suite files, two separate thread-pool dimensions, per-group filtering — grew organically over many years.
Sleuth is an opinionated take on the same idea, with the following non-negotiables:
-
Dependencies are first-class at both tiers. A suite can depend on another suite; a test can depend on another test. When a prerequisite fails, its downstream nodes are skipped and the original failure (the "culprit") is propagated with them.
-
Configuration lives in code. There is no
testng.xmlanalogue. Group membership, priority, ordering, and hard-versus-soft constraints are all expressed as annotation attributes on Java classes and methods. -
Parallelism is bounded by a single
threadCount. One pool, one knob. Fair semaphores gate two tiers (suite and test), so the framework will use every thread it can justify given the dependency graph — and never more. -
Migration is cheap. Existing TestNG test classes run under Sleuth without modification through a pluggable annotation translator layer.
-
Maven integration is a single JAR. Dropping
surefire-sleuth-providerinto the Surefire plugin’s<dependencies>block is all that is needed; no Mojos, no separate plugin, no extra phases.
The package name and its contents reflect that focus: a test runner that investigates the graph of relationships between tests, arranges them correctly, and reports who caused what.
The sleuth package is a Maven POM aggregator with two published artifacts:
| Artifact | Module | Module name | Purpose |
|---|---|---|---|
|
|
|
The framework proper: annotations, dependency resolution, thread pool, event system. No Maven dependencies; usable programmatically from any JVM host. |
|
|
|
A Surefire provider that adapts |
The sleuth-runner module name is the one to use in requires. Surefire loads surefire-sleuth-provider through its own class realms, so org.smallmind.sleuth.maven.surefire only identifies the jar; it is not intended for a consumer’s requires.
sleuth-runner ships an explicit module descriptor. It exports its three packages,
re-exports org.smallmind.nutsnbolts (requires transitive), and requires TestNG as the
automatic module org.testng, which it does not re-export. Tests normally run on the
classpath, where the descriptor is ignored. If you drive sleuth-runner on a module path,
open each test package to it, because it constructs test classes and invokes their annotated
methods reflectively:
opens com.example.app.tests to org.smallmind.sleuth.runner;See Module Path And Classpath for the repository-wide rules.
Depend on sleuth-runner if you are embedding Sleuth in another tool, driving it from a main method, or writing your own reporter. Depend on surefire-sleuth-provider (and only that) when you want mvn test to execute Sleuth-annotated classes.
Add the provider to the Surefire plugin’s <dependencies> block. Surefire will discover it through META-INF/services and delegate all test execution to Sleuth.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>surefire-sleuth-provider</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<configuration>
<properties>
<property>
<name>groups</name>
<value>smoke,regression</value>
</property>
<property>
<name>threadCount</name>
<value>4</value>
</property>
</properties>
</configuration>
</plugin>Write a suite:
package com.example;
import org.smallmind.sleuth.runner.annotation.AfterSuite;
import org.smallmind.sleuth.runner.annotation.BeforeSuite;
import org.smallmind.sleuth.runner.annotation.BeforeTest;
import org.smallmind.sleuth.runner.annotation.Suite;
import org.smallmind.sleuth.runner.annotation.Test;
import org.smallmind.sleuth.runner.TestContext;
@Suite(groups = {"smoke"})
public class AccountServiceTest {
@BeforeSuite
public void openDb () {
TestContext.put("db", Database.connect());
}
@AfterSuite
public void closeDb () {
TestContext.get("db", Database.class).close();
}
@BeforeTest
public void beginTx () {
TestContext.put("tx", TestContext.get("db", Database.class).begin());
}
@Test(priority = 0)
public void createAccount () {
Account a = TestContext.get("tx", Transaction.class).create("alice");
assert a.id() != null;
}
@Test(priority = 1, dependsOn = "createAccount")
public void readAccount () {
// only runs if createAccount passed
}
}Run it:
mvn test
mvn -Dgroups=smoke test
mvn -Dgroups=all testThe -Dgroups=all sentinel disables group filtering entirely and runs every annotated suite.
If you are not using Maven, instantiate SleuthRunner directly:
SleuthRunner runner = new SleuthRunner();
runner.addListener(event -> System.out.println(event));
runner.execute(
new String[] {"smoke"}, // groups
4, // threadCount
true, // stopOnError
true, // stopOnFailure
AccountServiceTest.class,
OrderServiceTest.class);Sleuth’s own annotations live in org.smallmind.sleuth.runner.annotation. All are retained at runtime.
| Attribute | Type | Default | Purpose |
|---|---|---|---|
|
|
(required) |
Group names this suite belongs to. Group filter selects suites by intersection. An empty array means the suite belongs to no named group and is excluded when any filter is active. |
|
|
|
Cross-suite ordering tier. Lower tiers are fully drained before higher tiers begin. |
|
|
|
Fully-qualified class names of suites that must complete (any outcome) before this one starts. Soft ordering; no culprit propagation. |
|
|
|
Fully-qualified class names of suites that must succeed before this one starts. Hard dependency; culprit is inherited and the suite is skipped if any prerequisite failed. |
|
|
|
When |
|
Note
|
Groups are declared on the suite, not on individual tests. This is deliberate: the unit of opt-in is the class. |
| Attribute | Type | Default | Purpose |
|---|---|---|---|
|
|
|
Intra-suite ordering tier. Lower tiers run first. |
|
|
|
Method names in the same suite that must complete before this test starts. Soft ordering. |
|
|
|
Method names in the same suite that must succeed before this test starts. Hard dependency. |
|
|
|
Exception types the test method is expected to throw. If the method throws one of the listed types, the test is reported as |
|
|
|
When |
A @Test method must take no arguments. Return values are ignored.
When expectedExceptions is empty (the default), an AssertionError escaping the method produces a FAILURE event; any other exception produces an ERROR event. The two are reported distinctly because one represents a broken expectation and the other represents broken code (or broken environment) — they deserve different triage.
When expectedExceptions is non-empty, entries that are not subtypes of Exception are silently ignored. For entries that are subtypes of Exception: if the thrown exception is an instance of a listed type, the test is reported as SUCCESS. If at least one Exception-subtype entry was present but none matched, the test is reported as FAILURE. If the list contains no Exception-subtype entries at all (e.g., only Error types), it is treated as absent and normal exception handling applies.
Four lifecycle annotations. @AfterSuite and @AfterTest carry a single alwaysRun attribute (default false); the two before-annotations have none. Multiple methods in a class (including inherited ones) may carry any of them; they run in class-hierarchy order, superclass methods first.
| Annotation | When it fires | If it throws |
|---|---|---|
|
Once, before the first |
A culprit is recorded; every subsequent |
|
Once, after the last |
Produces an |
|
Once per |
A culprit is recorded for the upcoming test, causing it to be skipped. |
|
Once per |
Produces an |
There isn’t one, by design. Anything you would put in a TestNG XML file — group composition, suite inclusion, ordering — is expressed on the classes themselves, and the filter surface is just the groups parameter. See TestNG Interoperability for running TestNG test classes unmodified.
Sleuth separates two concerns that TestNG conflates:
| Constraint | Semantics |
|---|---|
|
"Don’t start me until the named node has finished." Outcome of the named node is irrelevant; this node still runs no matter what. |
|
"Don’t start me unless the named node succeeded." If any named prerequisite failed, this node is skipped and inherits the prerequisite’s culprit. |
The distinction matters. Consider an integration test where reconcile() must run after insert() (because it reads the same rows) but should still run even if insert() produced a failure (because reconciliation is the thing you want to know about). That is executeAfter, not dependsOn. Conversely, readAccount has no reason to run if createAccount never produced an account — that is dependsOn.
Priority is a scheduling tier, not a sort key. All nodes sharing priority p may run concurrently; no node with priority p+1 may start until every node with priority p has completed. Priorities compose cleanly with explicit dependsOn / executeAfter — a priority-1 node implicitly executes after every priority-0 node, whether or not it names any of them.
When a test or suite fails, a Culprit is created. It walks the throwable chain looking for the first stack frame whose class name matches the node that threw (the test class or suite class), and records that frame plus the underlying throwable. The culprit rides along with the dependency node, and when the DependencyQueue later unblocks a dependent node, it copies the culprit over before dispatching. The skipped node emits a SkippedSleuthEvent whose message names the original culprit — so "test X was skipped because test Y failed at line 42 with AssertionError" is visible all the way down the chain.
At the start of every run the SleuthRunner partitions suites by group membership. A suite is included iff its groups array intersects the requested filter. Special cases:
-
groups == null(no filter was supplied): all suites run. -
groups == new String[0](empty filter): all suites run. The Surefire provider uses this to represent-Dgroups=all. -
Non-empty filter: at least one suite group must match at least one filter entry.
Filtered-out suites never enter the dependency graph, which means a suite filtered out by group cannot cause dependents to be skipped through dependsOn. If you have "don’t run me unless X ran too" semantics, you need to include X’s group in the filter; you can’t rely on skip-propagation to do it for you.
DependencyAnalysis.calculate() performs an iterative DFS topological sort with two invariants: every node is reachable, and the graph is acyclic. A cycle (A depends on B depends on A) throws TestDependencyException before any test executes. A dangling reference (A depends on B but B was never discovered, either because it has no @Test or because its class was filtered out) likewise throws TestDependencyException. Both failures prevent the run from starting rather than being discovered half-way through.
A complete run looks like this:
-
SleuthRunner.execute(…)creates aSleuthThreadPool(threadCount)and anAnnotationProcessorwith the native translator followed by the TestNG translator. -
For each candidate class, the processor returns an
AnnotationDictionary(ornullif the class is not a recognized suite). Enabled, in-group suites becomeDependencynodes in aDependencyAnalysis<Suite, Class<?>>. -
calculate()produces a topologically sortedDependencyQueue<Suite, Class<?>>. -
A
CountDownLatchis initialized to the queue size. The main thread drains the queue in a loop: each ready suite is dispatched to the pool as aSuiteRunner, blocking on theSUITE-tier semaphore when all threads are busy. -
Each
SuiteRunner:-
Reflectively instantiates the test class (requires a public no-arg constructor, otherwise
TestProcessingException). -
Invokes
@BeforeSuitemethods viaAnnotationMethodology.invoke(…). A throwing setup records a culprit. -
Builds a per-suite
DependencyAnalysis<Test, Method>from the suite’s@Testmethods. -
Drains the per-suite
DependencyQueue, dispatching each ready test as aTestRunneron theTEST-tier semaphore. -
Awaits a per-suite
CountDownLatch. -
Invokes
@AfterSuitemethods. Test failures do not suppress them; a@BeforeSuitefailure skips those not markedalwaysRun, and a culprit inherited from adependsOnprerequisite skips all of them. -
Stores the final culprit on its dependency node and calls
complete(), which releases its semaphore permit, marks the suite done in the queue (waking threads blocked inpoll()), and decrements the global suite latch.
-
-
Each
TestRunner:-
Invokes
@BeforeTestmethods. Any failure becomes the initial culprit for the test body. -
Fires
StartSleuthEvent. If a culprit exists (from setup or from a faileddependsOnprerequisite), firesSkippedSleuthEventand proceeds to teardown. -
Otherwise invokes the
@Testmethod. If it returns normally and theexpectedExceptionslist contains at least oneExceptionsubtype, aFailureSleuthEventis fired for the missing throw; otherwiseSuccessSleuthEvent. If it throws, the exception is checked againstexpectedExceptions: a matchingException-subtype entry →SuccessSleuthEvent; a non-matchingException-subtype entry or anAssertionError→FailureSleuthEvent; any other exception →ErrorSleuthEvent. -
Invokes
@AfterTestmethods if the test body ran, whether it passed or failed; if the body was skipped, only hooks markedalwaysRunare invoked. A hook failure becomes the culprit only when the test did not already fail. -
Calls
complete().
-
-
When the global latch reaches zero,
execute()returns. If the run was cancelled mid-flight aCancelledSleuthEventis fired in lieu of awaiting the latch.
If @BeforeSuite throws, every @Test in that suite emits a SkippedSleuthEvent, as does every @AfterSuite not marked alwaysRun = true (after firing their own StartSleuthEvent); alwaysRun after-suite hooks still run so they can release whatever setup acquired before it failed, and an exception they throw is reported as an ERROR without replacing the original culprit. If @BeforeTest throws, only the corresponding @Test and its non-alwaysRun @AfterTest hooks are skipped — the rest of the suite is untouched. This is the intended symmetry: a suite-level fixture is a suite-level responsibility, a test-level fixture is a test-level one.
A culprit inherited from a failed dependsOn suite is different: nothing in the dependent suite was ever set up, so every @BeforeSuite, @Test, and @AfterSuite there is skipped, alwaysRun included.
Sleuth is built around a typed event hierarchy and a single listener interface:
package org.smallmind.sleuth.runner.event;
public interface SleuthEventListener extends java.util.EventListener {
void handle (SleuthEvent event);
}Events are dispatched synchronously on the thread that fires them. Listeners must be thread-safe.
SleuthEvent (className, methodName; abstract)
├── CancelledSleuthEvent (CANCELLED)
└── TimedSleuthEvent (+ elapsed: long; abstract)
├── SuccessSleuthEvent (SUCCESS)
├── ThrowableSleuthEvent (+ throwable: Throwable; abstract)
│ ├── FailureSleuthEvent (FAILURE — AssertionError)
│ ├── ErrorSleuthEvent (ERROR — any other exception)
│ └── FatalSleuthEvent (FATAL — runner-level abort)
└── MessageSleuthEvent (+ message: String; abstract)
└── SkippedSleuthEvent (SKIPPED — culprit-driven)Additionally StartSleuthEvent (type START) extends SleuthEvent directly because nothing has been timed yet when it fires.
Each concrete event exposes getType() returning a SleuthEventType. Listeners that want to switch over type instead of instanceof should do so on this enum. The Surefire integration takes this approach; UnknownSwitchCaseException is thrown if a new enum constant is ever added without updating the switch, which means the compiler, not runtime, catches the drift.
SleuthRunner runner = new SleuthRunner();
runner.addListener(event -> {
switch (event.getType()) {
case START: System.out.println(">> " + event.getClassName() + "." + event.getMethodName()); break;
case SUCCESS: System.out.println("ok"); break;
case FAILURE:
case ERROR: {
ThrowableSleuthEvent t = (ThrowableSleuthEvent) event;
t.getThrowable().printStackTrace();
break;
}
case SKIPPED: System.out.println("skipped: " + ((SkippedSleuthEvent) event).getMessage()); break;
default: break;
}
});Every SleuthEvent also overrides toString() to produce an ANSI-colored one-line summary via AnsiColor, which is why System.out.println(event) works out of the box from the quick-start example.
Because all @Test methods in a suite are invoked on the same instance of the test class, and because several of those methods may run concurrently, mutable instance fields are a hazard. Sleuth provides TestContext as the canonical alternative:
public final class TestContext {
public static <T> T get (String key, Class<T> type);
public static Object get (String key);
public static void put (String key, Object value);
public static Object putIfAbsent (String key, Object value);
}The backing store is an InheritableThreadLocal<HashMap<String, Object>>. This has two consequences:
-
Values set on the suite thread (by
@BeforeSuite) are automatically visible to the child threads spawned for individual tests, becauseInheritableThreadLocalcopies to child threads at creation. -
Values set inside a
@Testor@BeforeTestare scoped to that test’s thread only, and will not bleed into sibling tests running on other threads.
The typical pattern is: expensive, read-only resources (database connections, HTTP clients, parsed configuration) are put into the context in @BeforeSuite; per-test state (a fresh transaction, a fresh captured event buffer) is put in @BeforeTest.
A single SleuthThreadPool is shared across the entire run. It holds two fair Semaphore instances — one per TestTier — each seeded with threadCount permits.
| Tier | Governs |
|---|---|
|
Number of simultaneously executing |
|
Number of simultaneously executing |
The second point matters: the TEST semaphore is not per-suite. If threadCount = 4 and two suites are open, up to 4 @Test methods can run in parallel between them, not 4 per suite. This is the intentional policy — threadCount is a budget for the machine as a whole, not per suite.
SleuthThreadPool does not reuse threads. Every TestController runs on a freshly spawned Thread. This is cheap enough in practice and avoids subtle interactions with thread-locals in user code. When a controller finishes it calls complete(), which releases its permit so a blocked dispatcher can proceed.
SleuthRunner.cancel() flips an AtomicBoolean. Already-running controllers finish their current lifecycle method; the dispatcher stops handing out new work and calls complete() directly on any controller it would have launched, which keeps the latches monotonic. A CancelledSleuthEvent is fired once the dispatcher loop observes the flag.
Cancellation is also triggered automatically by stopOnError=true (any ERROR event) and stopOnFailure=true (any FAILURE event). The Surefire provider sets both to true by default; setting testFailureIgnore=true in the plugin configuration flips both to false, producing "run everything, report everything" semantics.
Sleuth bundles a second AnnotationTranslator that recognizes TestNG’s annotation set and produces equivalent Sleuth dictionaries. Classes annotated with TestNG run unmodified as Sleuth suites, subject to the following mapping:
| TestNG | Sleuth | Notes |
|---|---|---|
Class-level |
|
Maps |
|
|
|
|
|
Maps |
|
|
|
|
|
Maps |
Method-level |
|
Maps |
The native translator runs first, so if a class carries both dialects (unusual, but legal) the Sleuth annotations win. TestNG’s @BeforeTest and @AfterTest (which operate on TestNG’s XML <test> tag, not on individual methods) are intentionally not mapped — there is no equivalent concept in Sleuth.
This translator layer is pluggable. To add, for example, a JUnit 4 translator, implement AnnotationTranslator and register it with the AnnotationProcessor. The existing SleuthRunner hard-codes new AnnotationProcessor(new NativeAnnotationTranslator(), new TestNGAnnotationTranslator()); embedders who need a different chain can build their own execution path reusing the rest of the framework.
The surefire-sleuth-provider JAR contains a single SurefireProvider service implementation plus supporting classes that plug Sleuth into the Maven Surefire reporting pipeline.
Surefire uses the standard Java service loader. The JAR ships with:
META-INF/services/org.apache.maven.surefire.api.provider.SurefireProvidercontaining one line:
org.smallmind.sleuth.maven.surefire.SleuthProviderWhen Surefire starts, it discovers this provider and delegates discovery and execution to it. No <configuration> switch is needed to select it — Surefire picks whichever provider is on its plugin classpath.
All configuration is read from either JVM system properties or the provider’s <properties> block:
| Property | Source | Default | Effect |
|---|---|---|---|
|
|
(none) |
Comma-separated group names to include. The sentinel value |
|
provider property |
|
Semaphore permits per tier. |
|
provider property |
|
When |
-
getSuites()callsproviderParameters.getScanResult().applyFilter(null, …)— i.e. delegates classpath scanning to Surefire’s normal mechanism. Sleuth does not scan the classpath itself. -
invoke(Object forkTestSet):-
Replaces
System.outandSystem.errwithForwardingPrintStreaminstances so that stdout/stderr produced by a test is correlated with that test’sTestIdentifierand written as aTestOutputReportEntryon the Surefire listener — meaning the Surefire XML report attributes console output to the right test even under parallel execution. -
Reads
groups,threadCount, andtestFailureIgnore. -
Registers a
SurefireSleuthEventListenerthat maps Sleuth events onto SurefireRunListenercallbacks. -
Calls
testSetStartingon the reporter, runssleuthRunner.execute(…), then callstestSetCompleted. -
If a
FatalSleuthEventwas captured, throwsTestSetFailedExceptionso Maven marks the build failed. -
Closes the
ReporterFactoryand returns the aggregatedRunResult.
-
| Sleuth event type | Surefire callback | Carries |
|---|---|---|
|
|
— |
|
|
elapsed ms |
|
|
|
|
|
|
|
|
skip message (names the culprit) |
|
|
— |
|
|
— |
SleuthStackTraceWriter is the bridge between a Sleuth Culprit and Surefire’s StackTraceWriter contract. Its smartTrimmedStackTrace() delegates to Culprit.toString(), producing short lines like:
com.example.AccountServiceTest.createAccount:42 AssertionError expected: <true> but was: <false>This section describes the internals, for readers who want to extend or embed Sleuth.
org.smallmind.sleuth.runner.SleuthRunner is the only public entry point. It owns:
-
A
LinkedList<SleuthEventListener>— registered listeners, fired synchronously in registration order. -
An
AtomicBoolean cancelled— flipped bycancel().
Its two execute overloads differ only in whether they accept varargs or an Iterable. Both go through the same pipeline described under [_lifecycle_step_by_step].
AnnotationProcessor holds an ordered array of AnnotationTranslator implementations and a HashMap<Class<?>, AnnotationDictionary> cache. process(Class<?>) is synchronized because the cache is shared across every SuiteRunner. For each class it walks translators in order and returns the first dictionary whose isImplemented() method returns true (i.e. it actually found Sleuth-or-equivalent annotations). A class that matches no translator is silently skipped.
An AnnotationDictionary holds the Suite (class-level) plus up to five AnnotationMethodology<A> instances — one per lifecycle annotation kind, plus one for @Test. An AnnotationMethodology is an ordered, deduplicated collection of (Method, A) pairs. Deduplication is by MethodKey (method name + parameter types), so when MethodCensus walks the class hierarchy superclass-first, an overriding subclass method naturally replaces the superclass entry.
AnnotationMethodology.invoke(SleuthRunner, Culprit, Class<?>, Object) is the single entry point that fires a batch of lifecycle methods. It emits a StartSleuthEvent before each method, a SuccessSleuthEvent or ErrorSleuthEvent after, and SkippedSleuthEvent for every method encountered once a culprit exists. The five-argument overload takes a Predicate<A> naming the annotations whose methods run anyway (the runners pass AfterSuite::alwaysRun and AfterTest::alwaysRun); a method that throws while a culprit already exists is reported as an ERROR but does not replace that culprit. The method returns the (possibly updated) culprit so the caller can chain calls.
The dependency engine is fully generic: Dependency<A, T> parameterizes over the annotation type (Suite or Test) and the payload type (Class<?> or Method). The engine has no knowledge of Sleuth-specific semantics; it operates only on name, priority, executeAfter, dependsOn, expectedExceptions, and children.
DependencyAnalysis.calculate() does two things:
-
Priority wiring. If there are multiple distinct priority values, every node in each lower tier becomes a parent of every node in the next tier, and the array of lower-tier names is stored on the higher-tier node as
priorityOn. This is how "all priority-0 before any priority-1" is enforced without the user typingexecuteAftereverywhere. -
Topological sort. Iterative DFS with cycle detection. The result is a
LinkedList<Dependency>in execution order.
DependencyQueue.poll() is a synchronized, blocking dequeue. It scans the list for any node whose dependsOn, executeAfter, and priorityOn arrays are entirely contained in the completedSet. For dependsOn specifically, if the prerequisite was completed but failed, the prerequisite’s culprit is copied into the candidate before it is returned. If no node is ready and the list is non-empty, the calling thread wait()`s. `complete(Dependency) adds the node to the completedSet and `notifyAll()`s.
SleuthThreadPool holds two java.util.concurrent.Semaphore instances, one per TestTier (SUITE, TEST), each initialized with threadCount fair permits. execute(TestTier, TestController):
-
Blocks on
acquire()of the tier’s semaphore. -
If the runner is no longer running (
cancel()was called), callscontroller.complete()directly — which releases the permit and decrements the owning latch — without starting a thread. -
Otherwise spawns a new
Thread(controller)and starts it.
There is no thread reuse. If this matters for an embedder, implementing a custom TestController host is straightforward: the interface is just Runnable plus complete().
Culprit records the origin of a failure by walking the throwable chain (via getCause()) and searching each throwable’s stack trace for the first frame whose class name matches the node that threw. The pair (matching throwable, matching frame) is what survives, so that a wrapped-and-rethrown failure still reports the original line in the original test class. Culprit.toString() is the compact one-liner seen in skip messages and Surefire trimmed stack traces.
Every time a SuiteRunner or TestRunner is about to dispatch a method, TestIdentifier.updateIdentifier(className, methodName) is called on the spawning thread. TestIdentifier maintains a static HashMap<TestKey, Long> — keyed on a (className, methodName) composite in which methodName is null for suite-level entries — assigning a stable long to each pair it ever sees, plus an AtomicLong counter and an InheritableThreadLocal<Long> holding the current thread’s id (default 1, inherited by child test threads). Allocation uses double-checked locking on the map. The Surefire provider reads this id when constructing every SimpleReportEntry and TestOutputReportEntry, ensuring that each Surefire event is attributable to the exact test that produced it — even stdout/stderr lines written from deep inside a service under test.
@Suite(groups = {"integration"})
public class OrderLifecycleTest {
@BeforeSuite public void openDb () { TestContext.put("db", Database.connect()); }
@AfterSuite public void closeDb () { TestContext.get("db", Database.class).close(); }
@Test(priority = 0)
public void placeOrder () {
Order o = TestContext.get("db", Database.class).orders().place("SKU-1", 3);
TestContext.put("orderId", o.id());
assert o.status() == PENDING;
}
@Test(priority = 1, dependsOn = "placeOrder")
public void shipOrder () {
String id = TestContext.get("orderId", String.class);
TestContext.get("db", Database.class).orders().ship(id);
}
@Test(priority = 2, dependsOn = "shipOrder")
public void deliverOrder () { ... }
@Test(priority = 2, executeAfter = "shipOrder")
public void auditTrailRecordedShipment () {
// runs concurrently with deliverOrder, but not before shipOrder is done;
// still runs even if shipOrder failed — that's the point of executeAfter
}
}A failure in placeOrder cascades: shipOrder, deliverOrder, and auditTrailRecordedShipment are all skipped with placeOrder’s culprit. A failure in `shipOrder skips deliverOrder (hard dep) but lets auditTrailRecordedShipment run anyway.
@Suite(groups = {"e2e"})
public class UserSetupSuite {
@Test public void createTenant () { ... }
@Test(dependsOn = "createTenant") public void createAdminUser () { ... }
}
@Suite(groups = {"e2e"}, dependsOn = "com.example.UserSetupSuite")
public class BillingSuite {
@Test public void configureBillingPlan () { ... }
}BillingSuite is held back until UserSetupSuite has fully run and completed without a culprit. If either test in UserSetupSuite fails, every test in BillingSuite is skipped.
public class HistogramListener implements SleuthEventListener {
private final EnumMap<SleuthEventType, AtomicInteger> counts = new EnumMap<>(SleuthEventType.class);
@Override public void handle (SleuthEvent event) {
counts.computeIfAbsent(event.getType(), k -> new AtomicInteger()).incrementAndGet();
}
public void print () {
counts.forEach((k, v) -> System.out.println(k + " = " + v.get()));
}
}import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
@Test(groups = {"smoke"})
public class LegacyTestNgTest {
@BeforeClass public void setup () { ... }
@Test(priority = 1) public void a () { ... }
@Test(priority = 2, dependsOnMethods = "a") public void b () { ... }
}TestNGAnnotationTranslator produces a dictionary equivalent to the Sleuth-native version above, so this class runs exactly as it would have under TestNG (modulo Sleuth’s concurrency model and event taxonomy).
| Exception | Thrown when |
|---|---|
|
The dependency graph contains a cycle, or a |
|
A suite class cannot be instantiated — usually because it lacks a public no-arg constructor — or the constructor itself threw. |
The runner module lives under sleuth/runner/src/main/java/org/smallmind/sleuth/.
File (relative to sleuth/runner/src/main/java/org/smallmind/sleuth/) |
Role |
|---|---|
|
Public entry point; listener registry, cancellation, and suite dispatch. |
|
Executes one suite’s full lifecycle. |
|
Executes one test method’s full lifecycle. |
|
Interface: |
|
Two-tier semaphore-based concurrency gate. |
|
Enum: |
|
Graph node. |
|
Builds the graph and topologically sorts it. |
|
Blocking ready-queue with culprit propagation. |
|
Failure-origin record. |
|
Inheritable thread-local fixture store. |
|
Stable per-test id for output correlation. |
|
Cycle or missing-dependency error. |
|
Suite instantiation failure. |
|
Sleuth’s annotation set. |
|
Programmatic annotation instances, one per annotation (used by translators). |
|
Strategy interface. |
|
Recognizes Sleuth’s own annotations. |
|
Recognizes TestNG annotations. |
|
Caches the translator-chain output. |
|
Per-class scan result. |
|
Ordered, deduplicated |
|
Iterates the class hierarchy. |
|
Abstract event root. |
|
Observer interface. |
|
Discriminator enum. |
|
Abstract mixins adding |
|
Concrete events. |
The maven/surefire module lives under sleuth/maven/surefire/src/main/.
| File | Role |
|---|---|
|
The |
|
Translates Sleuth events into Surefire |
|
Bridge between |
|
Wraps output entries with |
|
Replaces |
|
|
|
Service-loader descriptor registering |