Integration with Spring Framework

Sniffy comes with a Spring Framework via SniffySpringTestListener spring @TestExecutionListener. Just add @TestExecutionListeners(SniffySpringTestListener.class) to your Spring test class and place appropriate expectations on your test methods like shown below.

package io.sniffy.test.spring.usage;

import io.sniffy.socket.DisableSockets;
import io.sniffy.sql.SqlExpectation;
import io.sniffy.test.Count;
import io.sniffy.test.spring.SniffySpringTestListener;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringUsageTest.class)
@TestExecutionListeners(SniffySpringTestListener.class) (1)
public class SpringUsageTest {

    @Test
    @SqlExpectation(count = @Count(1)) (2)
    public void testJUnitIntegration() throws SQLException {
        final Connection connection = DriverManager.getConnection("sniffy:jdbc:h2:mem:", "sa", "sa"); (3)
        connection.createStatement().execute("SELECT 1 FROM DUAL"); (4)
    }

    @Test
    @DisableSockets (5)
    public void testDisableSockets() throws IOException {
        try {
            new Socket("google.com", 22); (6)
            fail("Sniffy should have thrown ConnectException");
        } catch (ConnectException e) {
            assertNotNull(e);
        }
    }

}
  1. - Integrate Sniffy to your test using @TestExecutionListeners(SniffySpringTestListener.class).

  2. - Now just add @SqlExpectation annotation to define number of queries allowed for given method.

  3. - Just add sniffy: in front of your JDBC connection URL in order to enable sniffer.

  4. - Do not make any changes in your code - just add the @TestExecutionListeners(SniffySpringTestListener.class) and put annotations on your test method.

  5. - Add @DisableSockets annotation on your test method or test class and any attempt to open a network connection will fail

  6. - All socket operations executed within test method annotated with @DisableSockets will throw a java.net.ConnectException