You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为PostgreSQL数据库实现Cucumber测试并配置后台连接

实现Cucumber与PostgreSQL数据库的集成测试

没问题,我来帮你梳理怎么实现这个需求——把数据库连接作为Cucumber的Background执行,同时让步骤执行查询并验证结果。咱们一步步来调整:

1. 重构DatabaseConnection类

原来的类把连接建立和查询逻辑混在一起了,不利于复用和测试维护。我们把它拆分成连接管理和查询执行两个独立部分,同时用PreparedStatement避免SQL注入风险:

import java.sql.*;

public class DatabaseConnection {
    private Connection con;

    // 建立数据库连接(供Background步骤调用)
    public void establishConnection() throws Exception {
        try {
            String dbUrl = "jdbc:postgresql://localhost:5432/test";
            String username = "postgres";
            String password = "12345678";
            
            Class.forName("org.postgresql.Driver");
            con = DriverManager.getConnection(dbUrl, username, password);
        } catch(SQLException e) {
            throw new RuntimeException("数据库连接失败", e);
        }
    }

    // 执行查询并返回结果(供Scenario步骤调用)
    public String executeNameQuery(int recordId) throws SQLException {
        String query = "select name from test where no = ?;";
        try (PreparedStatement stmt = con.prepareStatement(query)) {
            stmt.setInt(1, recordId);
            ResultSet rs = stmt.executeQuery();
            return rs.next() ? rs.getString("name") : null;
        }
    }

    // 关闭连接(测试结束后释放资源)
    public void closeConnection() throws SQLException {
        if (con != null && !con.isClosed()) {
            con.close();
        }
    }
}

2. 编写Cucumber步骤定义类

创建一个步骤绑定类,把Feature文件里的自然语言步骤和Java代码关联起来,同时管理数据库连接的生命周期:

import io.cucumber.java.After;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import static org.junit.Assert.assertEquals;

public class DatabaseSteps {
    private DatabaseConnection dbConnection;
    private String queryResult;

    // 对应Background的步骤:每个Scenario执行前先建立数据库连接
    @Given("I am connected with the database")
    public void connectToDatabase() throws Exception {
        dbConnection = new DatabaseConnection();
        dbConnection.establishConnection();
    }

    // 对应Scenario的查询步骤
    @When("I run the select query")
    public void executeSelectQuery() throws SQLException {
        // 这里查询no=1的记录,你可以根据需求调整参数
        queryResult = dbConnection.executeNameQuery(1);
    }

    // 对应结果验证步骤
    @Then("I should see the result as {string}")
    public void verifyQueryResult(String expectedName) {
        assertEquals("数据库查询结果不匹配", expectedName, queryResult);
    }

    // 测试结束后自动关闭连接,避免资源泄漏
    @After
    public void tearDownDatabaseConnection() throws SQLException {
        if (dbConnection != null) {
            dbConnection.closeConnection();
        }
    }
}

3. 确认Runner类配置

确保你的Runner类能扫描到Feature文件和步骤定义类:

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "src/test/resources/features", // 替换成你的Feature文件实际路径
        glue = "com.yourpackage.steps", // 替换成步骤定义类所在的包
        plugin = {"pretty", "html:target/cucumber-reports"}
)
public class TestRunner {
}

4. 验证Feature文件

你的Feature文件可以保持原样,因为步骤已经和代码完全绑定:

Feature: API Test
  Background: 
    Given I am connected with the database
  Scenario: I want to test the database connection
    When I run the select query
    Then I should see the result as "Pranjal"

这样运行Runner类后,Cucumber会先执行Background里的数据库连接步骤,再执行Scenario的查询和验证逻辑,完美实现你的需求。

内容的提问来源于stack exchange,提问作者Pranjal Prakash Srivastava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:42:33