简体   繁体   English

测试jdbc连接类

[英]Testing jdbc connection class

I try to learn to test my projects correctly and continuously. 我尝试学习正确,连续地测试我的项目。 Unfortunately there are a few things I don't understand since there are a lot of different opinions on the topic. 不幸的是,有些事情我不理解,因为对该主题有很多不同的看法。 What I don't get is how to decide which classes are „worth“ testing them. 我没有得到的是如何确定哪些类“值得”测试它们。 As an example I took the example JDBC connection class from oracle: 作为示例,我从oracle获取了示例JDBC连接类:

public Connection getConnection() throws SQLException {
    Connection conn = null;
    Properties connectionProps = new Properties();
    connectionProps.put("user", this.userName);
    connectionProps.put("password", this.password);
    if (this.dbms.equals("mysql")) {
        conn = DriverManager.getConnection(
                   "jdbc:" + this.dbms + "://" +
                   this.serverName +
                   ":" + this.portNumber + "/",
                   connectionProps);
    } else if (this.dbms.equals("derby")) {
        conn = DriverManager.getConnection(
                   "jdbc:" + this.dbms + ":" +
                   this.dbName +
                   ";create=true",
                   connectionProps);
    }
    System.out.println("Connected to database");
    return conn;
}
 

I know I can mock objects to be able to look at the class more isolated. 我知道我可以模拟对象,以便能够更孤立地查看类。 Is it even useful to test a class like this, or can I benefit from doing something like this, to see if a connection could theoretically be made? 测试这样的类甚至有用吗?或者我可以从这样的事情中受益,看看理论上是否可以建立连接?

public class TestClass {

    @Mock
    private Connection conn;

    @Mock
    private Database database;

    @BeforeEach
    public void setUp() throws Exception {
        assertNotNull(database);
        when(database.getConnection()).thenReturn(conn);
    }
}

Mocking in unit tests helps you test the part of your code that would otherwise be using a resource. 单元测试中的模拟可帮助您测试本应使用资源的代码部分。 Using it to test a class where it's only purpose is to establish connection to a resource makes no sense. 用它来测试仅用于建立与资源的连接的类是没有意义的。

This functionality will be tested during an integration testing. 此功能将在集成测试中进行测试。 See more on integration and unit testing here 在此处查看有关集成和单元测试的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM