[英]Unit testing in java
我必須為此Java程序添加測試。 但是,我不知道我可以在這種程序中使用什么測試。 我真的沒有看到使用測試的任何好處,因為它不是一個像查找數字是否為質數的程序。
package utcn;
import javax.swing.*;
import java.sql.*;
import java.awt.event.*;
public class BorrowBook extends JFrame implements ActionListener {
/**
* title will be the label for "Enter a book title" message
*/
JLabel title;
/**
* ttitle will be the field for introducing the title
*/
JTextField ttitle;
/**
* btn_borrow is the button for borrowing a book
*/
JButton btn_borrow;
/**
* This method will create a window for borrowing a book.
*/
public BorrowBook() {
super("BorrowBook");
title = new JLabel("Enter a book title:");
title.setBounds(20, 20, 200, 15);
ttitle = new JTextField(20);
ttitle.setBounds(130, 20, 220, 30);
btn_borrow = new JButton("BorrowBook");
btn_borrow.setBounds(220, 65, 100, 40);
btn_borrow.addActionListener(this);
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setSize(500, 150);
setLayout(null);
add(btn_borrow);
add(title);
add(ttitle);
}
/**
* This method will be called when the button is pressed. The application
* require for an book title. If the introduced title can be find in the
* database, it will be displayed a success message, otherwise an error
* message. Also, in the database, the nr_exempare will be decreased and the
* nr_imprumuturi will be increased.
*/
@Override
public void actionPerformed(ActionEvent ex) {
Connection conn = null;
PreparedStatement pst = null;
PreparedStatement pst1 = null;
ResultSet rs = null;
String title = ttitle.getText();
conn = MySqlConnect.ConnectDB();
try {
pst = conn.prepareStatement("update carti set nr_exemplare=nr_exemplare-1 where nume_carte=? ");
pst1 = conn.prepareStatement("update carti set nr_imprumuturi=nr_imprumuturi+1 where nume_carte=? ");
pst.setString(1, ttitle.getText());
pst1.setString(1, ttitle.getText());
int i = pst.executeUpdate();
int i1 = pst1.executeUpdate();
if ((i > 0) && (i1 > 0)) {
dispose();
JOptionPane.showMessageDialog(null, "Your book has been borrowed!");
} else {
JOptionPane.showMessageDialog(null, "Invalid book title.", "Accse Denied", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
您將很難在這里添加測試,因為您的方法可以完成所有工作:
通常,這些操作應在負責各自操作集的多個類和對象之間划分。
通常,您可以並且應該在此處進行測試的是,更新語句已相應執行,並且新數據就是您期望的數據。 但是要能夠正確測試,您將不得不更好地組織代碼。
從數據庫操作的業務邏輯中拆分UI。
測試應該檢查您的邏輯。 您不應該只考慮給出的正確數據。 用戶輸入奇怪的內容會怎樣?
或者,當您繼續開發代碼時。 假設通過其他功能對其進行了改進。 您可以確保舊內容仍然可以與已編寫的測試一起使用。
或者,當另一個開發人員處理您的代碼並且沒有閱讀您所有出色的工作時(以防代碼更長一點),他可以確保自己沒有剎車。
因此,在您的特定情況下,我建議您在輸入錯誤時測試是否顯示正確的錯誤。 還是兩次借書會發生什么? 像那樣的東西 ;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.