2016-04-20 149 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。如果这是真的,你的单元测试会通过,否则将失败。

还记得单元测试应该只测试一些单元,所以一些小的代码,但实际的功能。