Friday, March 01, 2013

JUnit Tests can still be run from a main method

I encountered a happy coincidence today: a JUnit test can just as easily be run from a main method. (Feel free to whisper sarcastically at this point. It was new to me!) I had begun with an old school main method test, when I realised I wanted to get more serious and write JUnit tests instead. I dutifully added my @Test methods and in an absent minded fashion ran the class as a Java application instead of a JUnit test (from within Eclipse). Lo and behold, whatever @Test method I called from main still works fine and gives meaningful error information if it fails.

package test;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

public class Tester {

 public static void main(String[] args) {
  Tester tester = new Tester();
  System.out.println("Test complete.");

 public void testSomething() {
  Assert.assertEquals(true, false);

And the output when this test fails.

Exception in thread "main" junit.framework.AssertionFailedError: expected:<true> but was:<false>
   at junit.framework.Assert.failNotEquals(
   at junit.framework.Assert.assertEquals(
   at junit.framework.Assert.assertEquals(
   at junit.framework.Assert.assertEquals(
   at test.Tester.testSomething(
   at test.Tester.main(