Junit基本用法
1.创建Junit Test Case
2.基本使用(以oracle数据库操作为例)
package com.csit.adminsystem1.tests;
import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.csit.adminsystem1.domains.TProduct;
import com.csit.adminsystem1.domains.TUser;
public class JdbcTest {
Connection conn;
//每次执行测试时调用,在这里为数据库连接操作
@Before
public void init() throws ClassNotFoundException, SQLException{
System.out.println("数据库初始化中...");
Class.forName("oracle.jdbc.driver.OracleDriver");
Properties po = new Properties();
po.put("user", "yourUsername");
po.put("password", "yourPassword");
conn = DriverManager.getConnection("jdbc:oracle:thin:127.0.0.1:1521:orcl", po);
}
//此处为调试内容,点击函数名,右键run as Junit Test
@Test
public void select() throws SQLException {
Statement ste = conn.createStatement();
ResultSet rs = ste.executeQuery("select * from t_product");
List<TProduct> users = new ArrayList<TProduct>();
while (rs.next()) {
TProduct user = new TProduct();
user.setProductId(rs.getInt("product_id"));
user.setProductName(rs.getString("product_name"));
user.setProductPrice(rs.getDouble("product_price"));
users.add(user);
}
System.out.println(users);
}
@Test
public void insert() throws SQLException {
Statement ste = conn.createStatement();
TProduct product = new TProduct(0, "可口可乐", 3.0);
StringBuffer sbf = new StringBuffer("insert into t_product (product_id,product_name,product_price) values(");
sbf.append(product.getProductId()).append(",");
sbf.append("'").append(product.getProductName() ).append("'").append(",");
sbf.append(product.getProductPrice()).append(")");
try{
ste.execute(sbf.toString());
}catch(Exception e) {
System.out.println("insert fail!"+e.getMessage());
throw e;
}
System.out.println("insert successful!");
}
@Test
public void delete() throws SQLException {
String sql = "delete from t_product where product_id = ?";
PreparedStatement ste = conn.prepareStatement(sql);
ste.setInt(1, 0);
try{
ste.execute();
}catch(Exception e) {
System.out.println("delete fail!"+e.getMessage());
throw e;
}
System.out.println("delete successful!");
}
//执行完毕后调用,关闭数据库
@After
public void end() throws SQLException {
conn.close();
System.out.println("over...");
}
}
分别执行查询,插入,查询,删除,查询操作后执行结果如下图: