junit单元测试

junit单元测试

(一)概述

	JUnit是一个Java语言的单元测试框架。它由Kent Beck和Erich Gamma建立,逐渐成为源于Kent Beck的sUnit的xUnit家族中最为成功的一个。 JUnit有它自己的JUnit扩展生态圈。多数Java的开发环境都已经集成了JUnit作为单元测试的工具。

(二)junit的使用

1. 把junit4.x的测试jar,添加到该项目中来;
2. 定义一个测试类 测试类的名字: XxxTest,如EmployeeDAOTest
3. 在EmployeeDAOTest中编写测试方法:如
 @Test
 public void testXxx() throws Exception {
 }
 注意:方法是public修饰的,无返回的,该方法上必须贴有@Test标签,XXX表示测试的功能名字
 
4. 选择某一个测试方法,鼠标右键选择 [run as junit],或则选中测试类,表示测试该类中所有的测试方法.

(三)常见注解

1. @Test:要执行的测试方法
2. @Before:每次执行测试方法之前都会执行
3. @After: 每次执行测试方法之后都会执行

(四)代码示例

`
package com.offcn.test;

import com.mysql.jdbc.Driver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.*;

public class JDBCTest {

private Connection connection;
private Statement st;
private ResultSet rs;

@Test
public void insert() throws SQLException {
    String sql = "insert into student values(null,'小明','广州',18)";
    int i = st.executeUpdate(sql);
    System.out.println(i > 0 ? "执行成功" : "执行失败");
}

@Test
public void delete() throws SQLException {
    String sql = "delete from times where id = 1";
    int i = st.executeUpdate(sql);
    System.out.println(i > 0 ? "执行成功" : "执行失败");
}

@Test
public void update() throws SQLException {
    String sql = "update times set state = '修改后' where id = 2";
    int i = st.executeUpdate(sql);
    System.out.println(i > 0 ? "执行成功" : "执行失败");
}

@Test
public void queryTest() throws SQLException {
    rs = st.executeQuery("select * from student");
    while (rs.next()) {
        System.out.println(
                "id:" + rs.getInt("id") +
                        "\tname:" + rs.getString("name") + "\tcity:" + rs.getString("city") + "\tage:" + rs.getInt("age")
        );
    }
}



@Before
public void before() throws SQLException {
    DriverManager.registerDriver(new Driver());
    String url = "jdbc:mysql://localhost:3306/day08";
    String username = "root";
    String password = "123";
    connection = DriverManager.getConnection(url, username, password);
    st = connection.createStatement();
}

@After
public void after() {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    if (st != null) {
        try {
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    if (connection != null) {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

}
`

posted @ 2021-09-06 08:42  HJ0101  阅读(153)  评论(0编辑  收藏  举报