2016-04-20 147 views
-1

我寫了一個正在工作的java代碼,但我必須爲它編寫一個Junit測試腳本,但我還沒有經驗。我嘗試了幾個小時,但我不明白它是如何工作的。所以你的幫助非常受歡迎。在此先感謝:)你有任何tipps給我嗎? :)通過,如果你想測試你是否錯誤處理工程測試您有一定的預期輸出,或不正確的輸出編寫的代碼如何編寫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(""); 
} 
} 
} 
+1

我的提示是正確縮進你的代碼,這對於你自己和其他人在閱讀代碼時的好處都是合適的。 –

回答

1

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(); 
     } 
    } 
2

我要說的是,在你的情況下,程序並沒有達到目前的水平時,應該進行單元測試。我沒有看到任何理由說明爲什麼你需要測試一些構造函數在初始化類的字段時以及程序打印某些內容時工作。我不會檢查。

在出現錯誤並且此錯誤可能包含不同錯誤消息的情況下,驗證消息是否相同是一個好主意,但這不是您的情況。所以,重點是你的單元測試應該測試業務邏輯

考慮此模板:

@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。如果這是真的,你的單元測試會通過,否則將失敗。

還記得單元測試應該只測試一些單元,所以一些小的代碼,但實際的功能。