[英]How to write a junit test script?
我寫了一個可以正常工作的Java代碼,但是我必須為此編寫一個Junit測試腳本,但是我還沒有經驗。 我嘗試了幾個小時,但我不明白它是如何工作的。 因此,非常歡迎您的幫助。 在此先感謝:)您有給我的小費嗎? :)
import java.awt.*;
import java.awt.event.*;
class MailBox extends Frame {
private boolean request;
private String message;
TextField tf1;
public MailBox() {
Dimension screenDim = getToolkit().getScreenSize();
Dimension frameDim = getPreferredSize();
setLocation((screenDim.width-frameDim.width)/2, (screenDim.heightframeDim.height)/2); addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
}
Panel myPanel = new Panel();
myPanel.setLayout(new FlowLayout());
Label label1 = new Label("Message: ");
Button button1 = new Button("Send");
button1.addActionListener(new button1AL());
tf1 = new TextField("", 20);
myPanel.add(label1);
myPanel.add(tf1);
myPanel.add(button1);
add(myPanel, BorderLayout.CENTER);
setTitle("Mailbox");
pack();
show();
}
public synchronized void storeMessage(String message){
while(request==true){
try{
wait();
}
catch(InterruptedException e){
}
}
request = true;
this.message = message;
notify();
}
public synchronized String retrieveMessage(){
while(request==false){
try{
wait();
}
catch(InterruptedException e){
}
}
request=false;
notify();
return message;
}
public static void main(String args[]) {
System.out.println("Starting Mailbox...");
MailBox MyMailBox = new MailBox();
Consumer c1 = new Consumer(MyMailBox);
Thread t1 = new Thread(c1);
t1.start();
}
class button1AL implements ActionListener{
public void actionPerformed(ActionEvent ae){
storeMessage(tf1.getText());
tf1.setText("");
}
}
}
我要說的是,在您的情況下,該程序尚未達到應進行單元測試的水平。 我看不出有什么理由需要測試某些構造函數是否在初始化類的字段以及程序輸出某些內容時起作用。 我不會檢查。
如果您遇到一些錯誤,並且此錯誤可能包含不同的錯誤消息,則最好確認消息是否相同,但這不是您的情況。 因此,重點是您的單元測試應該測試業務邏輯 。
考慮以下模板:
@Test
public void testGoUntilTankIsEmpty() throws Exception {
// SETUP SUT
Car car = new Car();
car.fillFullTank();
car.setSpeed(80);
// EXERCISE
int distanceInKm = car.goUntilTankIsEmpty();
// VERIFY
Assert.assertEquals(800, distanceInKm);
}
在這種情況下,我們將使用(測試)指定的方法,並根據我們的初步設置期望結果為800。 如果為真,則您的單元測試將通過,否則將失敗。
請記住,單元測試應該只測試某些單元,因此只測試一小段代碼,但是實際的功能。
JUnit的工作是測試您編寫的代碼的預期輸出結果,如果您想測試錯誤處理是否有效,則該代碼將具有預期輸出或錯誤輸出。
在您的情況下,您只需要針對它輸出的預期字符串進行測試。
因此,針對您所擁有的產品進行基本測試將看起來與...
import org.junit.Test;
import org.junit.Assert.assertEquals
public class BasicTest{
@Test
public void describeAnimalTest(){
AnimalNew animal = new AnimalNew("Dog", 10, "x");
assertEquals("Dog is on level 10 und is a type of x", animal.describeAnimal();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.