Using Sniffy API
Sniffy provides a convenient API for validating the number of executed database queries, affected database rows or even number of active TCP connections.
The main classes you should use are io.sniffy.Sniffy and io.sniffy.Spy.
Spy objects are responsible for recording the executed queries and bytes sent over the wire. Spy stores all the information since the moment it was created.
Sniffy class provides convenient factory methods for creating Spy instances
Imperative approach
Connection connection = DriverManager.getConnection("sniffy:jdbc:h2:mem:", "sa", "sa"); // (1)
Spy<?> spy = Sniffy.spy(); // (2)
connection.createStatement().execute("SELECT 1 FROM DUAL"); // (3)
spy.verify(SqlQueries.atMostOneQuery()); // (4)
spy.verify(SqlQueries.noneQueries().otherThreads()); // (5)
-
Just add
sniffy:in front of your JDBC connection URL in order to enable sniffer. -
Spyholds the amount of queries executed till the given amount of time. It acts as a base for further assertions. -
You do not need to modify your JDBC code.
-
spy.verify(SqlQueries.atMostOneQuery())throws an AssertionError if more than one query was executed. -
spy.verify(SqlQueries.noneQueries().otherThreads())throws an AssertionError if at least one query was executed by the thread other than then current one.
Functional approach
final Connection connection = DriverManager.getConnection("sniffy:jdbc:h2:mem:", "sa", "sa"); // (1)
Sniffy.execute(
() -> connection.createStatement().execute("SELECT 1 FROM DUAL")
).verify(SqlQueries.atMostOneQuery()); // (2)
-
Just add
sniffy:in front of your JDBC connection URL in order to enable sniffer. -
Sniffy.execute()method executes the lambda expression and returns an instance ofSpywhich provides methods for validating the number of executed queries in given lambda/
Resource approach
final Connection connection = DriverManager.getConnection("sniffy:jdbc:h2:mem:", "sa", "sa"); // (1)
try (@SuppressWarnings("unused") Spy s = Sniffy. // (2)
expect(SqlQueries.atMostOneQuery()).
expect(SqlQueries.noneQueries().otherThreads());
Statement statement = connection.createStatement()) {
statement.execute("SELECT 1 FROM DUAL");
}
-
Just add
sniffy:in front of your JDBC connection URL in order to enable sniffer. -
You can use
Sniffyin a try-with-resource block usingexpectmethods instead ofverify. When the try-with-resource block is completed, Sniffy will verify all the expectations defined