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;

@RunWith(JUnit4.class)
public class Tester {

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

 @Test
 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.fail(Assert.java:50)
   at junit.framework.Assert.failNotEquals(Assert.java:287)
   at junit.framework.Assert.assertEquals(Assert.java:67)
   at junit.framework.Assert.assertEquals(Assert.java:147)
   at junit.framework.Assert.assertEquals(Assert.java:153)
   at test.Tester.testSomething(Tester.java:20)
   at test.Tester.main(Tester.java:14)

Popular Posts