Connection Closed when Testing Repository using Testcontainers with JDBC Template

I am trying to test the below UserRepositoryImpl class that inserts a User into a MySql database.

@Repository
public class UserRepositoryImpl implements UserRepository {

    private final JdbcTemplate template;

    public UserRepositoryImpl(DataSource dataSource) {
        this.template = new JdbcTemplate(dataSource);
    }

    @Override
    public Integer insert(User user) {
        String sql = "INSERT INTO EXPENSE_TRACKER.USERS (USERNAME, PASSWORD, FIRSTNAME, LASTNAME, EMAIL) VALUES (?, ?, ?, ?, ?)";
        return template.update(sql, user.getUsername(), user.getPassword(), user.getFirstName(), user.getLastName(), user.getEmail());
    }
}

I need to test this method and for this reason, I have created the next simple test that uses Testcontainers.

@SpringBootTest
class UserRepositoryImplSpec extends TestContainersSpec {

    @Subject
    UserRepositoryImpl repository

    def setup() {
        repository = new UserRepositoryImpl(dataSource)
    }

    def "Successfully insert a new user in the database"() {
        given: "a user"
        def user = new User(username: 'testUser', password: 'myPassword', firstName: 'myName',
                lastName: 'myLastName', email: '[email protected]')

        when: "calling the insert method"
        def result = repository.insert(user)

        then: "the user is saved"
        def dbUser = sql.firstRow("SELECT * FROM EXPENSE_TRACKER.USERS WHERE USERNAME = ?", [user.username])
        assert dbUser != null
        assert dbUser.get('ID') == result
        assert dbUser.get('USERNAME') == user.username
        assert dbUser.get('PASSWORD') == user.password
        assert dbUser.get('FIRSTNAME') == user.firstName
        assert dbUser.get('LASTNAME') == user.lastName
        assert dbUser.get('EMAIL') == user.email
    }
}

The TestContainersSpec class besides the container itself utilizes the creation of a reusable network so that I can use the same container. I needed to find a way to configure my Datasource and I thought to mock it based on the Sql instance shown below. Since this is an integration test, I know that this is not the way to go (mocking), but I will see on how to change this later on.

class TestContainersSpec extends Specification {

    @Shared
    public static MySQLContainer mySQL

    public static Network network = createReusableNetwork('expense-network')

    @Shared
    Sql sql

    @Shared
    DataSource dataSource

    def setup() {
        mySQL = new MySQLContainer("mysql:8.0.28")
                .withExposedPorts(3306)
                .withDatabaseName('EXPENSE_TRACKER')
                .withUsername('root')
                .withPassword('test')
                .withNetwork(network)
                .withReuse(true)
                .withStartupTimeout(Duration.ofMinutes(3))
                .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("mySQL")))
        mySQL.start()

        dataSource = Mock()
        sql = Sql.newInstance(mySQL.jdbcUrl, mySQL.username, mySQL.password, mySQL.driverClassName)
        dataSource.connection >> sql.connection
        createLocalDb(sql)
    }

    def createLocalDb(Sql sql) {
        ['cleanup.sql', 'schema.sql'].collect{ path ->
            getClass().getResource("/$path").text.trim()
        }.each { queries ->
            queries.tokenize(";").each{
                try {
                    sql.execute(it)
                } catch(Exception e) {
                    println e.message
                }
            }
        }
        println 'Local database ready'
    }

    static Network createReusableNetwork(String name) {
        String id = DockerClientFactory.instance().client().listNetworksCmd().exec().stream()
                .filter(network -> network.getName().equals(name)
                        && network.getLabels() == DockerClientFactory.DEFAULT_LABELS)
                .map(com.github.dockerjava.api.model.Network::getId)
                .findFirst()
                .orElseGet(() -> DockerClientFactory.instance().client().createNetworkCmd()
                        .withName(name)
                        .withOptions(['mtu': '1350'])
                        .withCheckDuplicate(true)
                        .withLabels(DockerClientFactory.DEFAULT_LABELS)
                        .exec().getId())

        return new Network() {
            @Override
            String getId() {
                return id
            }

            @Override
            void close() {
            }

            @Override
            Statement apply(@NotNull Statement statement, @NotNull Description description) {
                return statement
            }
        }
    }
}

However, when I execute my test, I am getting the next error:

May 19, 2024 2:22:04 PM groovy.sql.Sql$AbstractQueryCommand execute
WARNING: Failed to execute: SELECT * FROM EXPENSE_TRACKER.USERS WHERE USERNAME = ? because: No operations allowed after connection closed.
May 19, 2024 2:22:04 PM groovy.sql.Sql$AbstractQueryCommand execute
WARNING: Failed to execute: SELECT * FROM EXPENSE_TRACKER.USERS WHERE USERNAME = ? because: No operations allowed after connection closed.

No operations allowed after connection closed.
java.sql.SQLNonTransientConnectionException: No operations allowed after connection closed.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:111)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:98)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:90)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:64)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:74)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:73)
    at com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1610)
    at groovy.sql.Sql$CreatePreparedStatementCommand.execute(Sql.java:4808)
    at groovy.sql.Sql$CreatePreparedStatementCommand.execute(Sql.java:4786)
    at groovy.sql.Sql.getAbstractStatement(Sql.java:4625)
    at groovy.sql.Sql.getPreparedStatement(Sql.java:4640)
    at groovy.sql.Sql.getPreparedStatement(Sql.java:4729)
    at groovy.sql.Sql.access$1000(Sql.java:234)
    at groovy.sql.Sql$PreparedQueryCommand.runQuery(Sql.java:4925)
    at groovy.sql.Sql$AbstractQueryCommand.execute(Sql.java:4856)
    at groovy.sql.Sql.rows(Sql.java:2050)
    at groovy.sql.Sql.rows(Sql.java:1980)
    at groovy.sql.Sql.rows(Sql.java:1824)
    at groovy.sql.Sql.firstRow(Sql.java:2295)
    at com.expense.tracker.repository.UserRepositoryImplSpec.Successfully insert a new user in the database(UserRepositoryImplSpec.groovy:27)
Caused by: com.mysql.cj.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:104)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:149)
    at com.mysql.cj.NativeSession.checkClosed(NativeSession.java:756)
    at com.mysql.cj.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:556)
    at com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1539)

I can’t see the reason, my connection closes. Can you propose me a solution?

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật