How to unit test the code?

1. When we verify whether the operation of our code is consistent with the expected operation result, we often call the method we wrote in the main function to run. This is a relatively common method.
2. What if we do not use the main method for testing? Take the database connection as an example, write a test class, including a main function, which is a common method

package com.zhouquan.jdbc.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MainTest {
 public static void main(String[] args) {
  try {
   Connection conn=JDBCUtil.getConnection();
   String sql="select * from t_stu";
   PreparedStatement ps= conn.prepareStatement(sql);
   ResultSet rs=ps.executeQuery();
   while(rs.next()) {
    String name=rs.getString("name");
    int age=rs.getInt("age");
    System.out.println("name="+name+"   age"+age);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
}

If using unit tests
we first

  1. Write a test class TestDemo.java, and then define a testxxx method
  2. Right click project –>add Library–>Junit—>Junit4
  3. Add annotations to class methods
public class TestDemo {
 @Test //单元测试的注解
   public void testQuery() {
   try {
   	***
  	}
    }
 }
  1. Right-click Run as to run.
    The green status bar on the left indicates that the program can run successfully.Note: It can be run successfully here, but it does not necessarily ensure that the running result of the code is correct!
    insert image description here
    If there is a problem with the program running, the status bar on the left will turn red

insert image description here
that's all.

Guess you like

Origin blog.csdn.net/qq_29864051/article/details/86681966