Java学习十四

学习内容:

1.Junit


一、Junit实例演示步骤

1.引入jar包

Java学习十四

 junit包需要引入hamcrest-core包,否则会报错

2.测试如下代码

package com.junit.test;

public class Calculator {
    private static int result; //静态变量,用于存储运行结果
    public void add(int n){
        result=result+n;
    }
    public void substract(int n){
        result=result-1; //Bug:正确的应该是result=result-n
    }
    public void multiply(int n){
        
    }//此方法尚未写好
    public void divide(int n)throws Exception{
        if(n==0)
            throw new Exception("除数不能为0");
        result=result/n;
    }
    public void square(int n){
        result=n*n;
    }
    public void squareRoot(int   n){
        for(;;);         //Bug:死循环
    }
    public void clear(){  //将结果清零
        result=0;
    }
}

3.进行单元测试

点击测试项目,点击新建JUnit Test Case

Java学习十四

选择测试方法

Java学习十四

 演示代码

package com.junit.test;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

public class CalculatorTest {
    
    public static Calculator c = new Calculator();
    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void testAdd() {
        c.add(2);
        c.add(2);
        assertEquals(4,c.getResult());
    }

    @Test
    public void testSubstract() {
        c.substract(2);
        assertEquals(2,c.getResult());
    }

    @Ignore
    public void testMultiply() {
        c.multiply(10);
    }

    @Test(expected = Exception.class)
    public void testDivide() throws Exception {
        c.divide(0);
    }

    @Test(timeout = 1000)
    public void testSquareRoot() {
        c.squareRoot(9);
    }

}

演示结果

Java学习十四

 其中将multiply方式用ignore注解忽略到了


另外一个测试代码演示带有数据库

待测试的项目:

package com.junit.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class Demo {
    Connection conn=null;
    public static void main(String[] args){
        //运行之前需要创建数据库和表格,参考test1.sql文件
        Demo d=new Demo();
        Map param=new HashMap();
        param.put("id",5);
        param.put("name","amy");
        param.put("password","123456");
        d.insert(param);
        d.getAll();
        d.close();
    }
    public void createDb(){
        String url="jdbc:mysql://localhost:3306/test1";
        String name="com.mysql.jdbc.Driver";
        String user="root";
        String password="root";
        try {
            Class.forName(name);//指定连接类型
             conn = DriverManager.getConnection(url, user,password);
             System.out.println("连接成功");
             //pst=conn.prepareStatement(sql);//准备执行语句
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch(SQLException e){
            e.printStackTrace();
        }
    }
    
    public int insert(Map param){
        this.createDb();
        int i=0;
        String sql="INSERT INTO user(id,username,password) VALUES(?,?,?)";
        PreparedStatement pstmt;
        try{
            pstmt=this.conn.prepareStatement(sql);
            pstmt.setString(1,(String)param.get("id"));
            pstmt.setString(2,(String)param.get("name"));
            pstmt.setString(3,(String)param.get("password"));
            i=pstmt.executeUpdate();
            pstmt.close();
        }catch(SQLException e){
            e.printStackTrace();
        }
        
        return i;
    }
    public void getAll(){
        String sql="select * from user";
        PreparedStatement pstmt=null;
        try{
            pstmt=this.conn.prepareStatement(sql);
            ResultSet rs=pstmt.executeQuery();
            int col=rs.getMetaData().getColumnCount();
            System.out.println("=========================");
            while(rs.next()){
                for(int i=1;i<=col;i++){
                    System.out.print(rs.getString(i)+"\t");
                    if((i==2)&&(rs.getString(i).length()<8)){
                        System.out.print("\t");
                    }
                }
                System.out.println("");
            }
            System.out.println("=========================");
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public void close(){
    }
}

测试代码

package com.junit.test;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Map;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class DemoTest {
    
    public static Demo d = new Demo();
    
    @Before
    public void setUp() throws Exception {
    }

    @Before
    public void testCreateDb() {
        d.createDb();
    }

    
    @Test
    public void testInsert() {
        Map param=new HashMap();
        param.put("id","2");
        param.put("name","amy");
        param.put("password","123456");
        d.insert(param);
    }

    @Test
    public void testGetAll() {
        d.getAll();
    }

    @After
    public void testClose() {
        d.close();
    }

}

测试结果

Java学习十四

 打包所有要测试的类

package com.junit.test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
    CalculatorTest.class,
    DemoTest.class
})

public class TestAllForJunit {

}

相关推荐