Simple Java Unit Test Framework

This is part of JavaUnitTestChallengeSolved -- DonWells


MS J++ was a complete disaster. It would not compile anything. I wanted J++ 1.1 because it works with JDK 1.0.2 for which I already had a unit TestingFramework. Anyway, I did also have Symantec Visual Caf� 2.5a. That took some getting used to, but after I had figured out how to get around those darn helpful code generating wizards, I was able to get some things done. Turns out that it is just as well since I could not find my old unit TestingFramework anyway. So now I look at JUnit written by KentBeck and ErichGamma. There are some good ideas here, but it is more than I need so I decide to just write my own version. I can steal a couple things though. My version has limitations but it is just as much as I need and no more.

The way this thing works is you write extensions (subclasses) of the class Test. You include a run() method that is invoked when the test is run. You call should(boolean, String) to test if things went well. Then you put an instance of that test into an array of tests in the method addTests() in the TestGUI class.

Included are three tests that test the framework. One each pass, fail, abort. A fail is when the test ran but the should() messages show a problem. An abort is when something causes a Java runtime error. When you run the framework on these three tests it should look like something like this except this version has two run buttons instead of one I think.

In file TestGUI.java

 import java.awt.*;
 import java.awt.event.*;

public class TestGUI extends Frame { static TestGUI testFrame; Label scoreLabel; List listOfTests; Test[] tests;

TestGUI(){ setLayout(new BorderLayout()); setSize(250,180); setTitle("Unit Tests"); addWindowListener(exitListener()); add(scoreLabel(), "North"); add(listOfTests(), "Center"); add(buttonPanel(), "South"); addTests(); showResults();}

public static void main(String arguments[]){ testFrame = new TestGUI(); testFrame.setVisible(true);}

public void addTests(){ tests = new Test[3]; tests[0] = new GoodTest(); tests[1] = new FailTest(); tests[2] = new AbortTest();}

void runTests() { for (int each = 0; each < tests.length; each++){ runOneTest(each);}}

void runOneTest(int anIndex) { tests[anIndex].runAndCaptureAborts();}

int selectedTest(){ return listOfTests.getSelectedIndex();}

private void showResults() { listOfTests.removeAll(); for (int each = 0; each < tests.length; each++) { listOfTests.add(tests[each].result);} showScore();}

private void showScore(){ int passed = numberPassed(); float total = (float) tests.length; int score = (int)(passed / total * 100); scoreLabel.setText(score + "%"); showPassFail(score);}

private int numberPassed (){ int passed = 0; for (int each = 0; each < tests.length; each++) { if (tests[each].success) { passed++;}} return passed;}

private void showPassFail (int aScore){ scoreLabel.setBackground((aScore == 100) ? Color.green : Color.red);}

private Label scoreLabel(){ return scoreLabel = new Label("Not Run", Label.CENTER);}

private List listOfTests (){ return listOfTests = new List(5);}

private Panel buttonPanel(){ Panel buttons = new Panel(); buttons.setLayout(new FlowLayout()); buttons.add(runButton()); buttons.add(runOneButton()); return buttons;}

private Button runButton() { Button button = new Button("Run Tests"); button.addActionListener (runButtonListener()); return button;}

private Button runOneButton() { Button button = new Button("Run Selected"); button.addActionListener (runOneButtonListener()); return button;}

private WindowAdapter exitListener(){ return new WindowAdapter() { public void windowClosing(WindowEvent anEvent) { System.exit(0);}};}

private ActionListener runButtonListener(){ return new ActionListener(){ public void actionPerformed(ActionEvent anEvent){ testFrame.runTests(); testFrame.showResults();}};}

private ActionListener runOneButtonListener(){ return new ActionListener(){ public void actionPerformed(ActionEvent anEvent){ testFrame.runOneTest(testFrame.selectedTest()); testFrame.showResults();}};} }

in file Test.java

 public class Test {
    public boolean success = false;
    public String result = "not run";

public void run()throws RuntimeException {}

public void should (boolean aTestPassed, String aMessage){ if (!aTestPassed) { throw new TestFailedException(aMessage);};}

public void runAndCaptureAborts() { try { runAndCaptureFailures();} catch (RuntimeException exception) { success = false; exception.fillInStackTrace(); result = message("Aborted : " + exception.getMessage());}}

private void runAndCaptureFailures()throws RuntimeException { try { runAndAllowExceptions();} catch (TestFailedException exception) { success = false; result = message("Failed : " + exception.getMessage());}}

private void runAndAllowExceptions()throws TestFailedException, RuntimeException { run(); success = true; result = message("Passed");}

private String message(String aString){ return getClass().getName() + " : " + aString;} }

in File TestFailedException.java

 public class TestFailedException extends java.lang.RuntimeException {

TestFailedException(String aMessage){ super(aMessage);} }

in File GoodTest.java

 public class GoodTest extends Test{

public void run(){ should (true, "This test always succeeds");} }

in file FailTest.java

 public class FailTest extends Test {

public void run() { should(false, "this test always fails");} }

in file AbortTest.java

 public class AbortTest extends Test {

public void run() { int two = 2; int zero = 0; should(two / zero == 0, "this test always fails");} }


CategoryJava


EditText of this page (last edited January 28, 2010) or FindPage with title or text search