CS3340:   Intro OOP and Design

 

JUnit Version

There has been a shift in how your Unit Testing code works between JUnit version 3 and 4.

However, depending on your IDE (and version) it may support version 3 over version 4.

 

 

JUnit 3

  • Extends TestCase class

JUnit 4

  • Does NOT extend TestCase class
  • INSTEAD you create test and lifecycle methods (setUp and tearDown) using Java 5 annotations.
  • Uses Annotations on Methods to indicate when run
  • assertEquals() & similar others, are imported as static

For example, the following is a valid JUnit 4-style test case (minus the necessary imports)

public class BusinessLogicTests {
  @Before
  public void do_this_before_every_test() {
    // set up logic goes here
  }

  @After
  public void clean_up_after_a_test() {
    // teardown logic goes here
  }

  @Test
  public void addition() {
    assertEquals("Invalid addition", 2, 1+1);
  }
}

 

JUnit 4 and Eclipse

Suppose you want to create a JUnit test class for the class "MyMath" that has
a method called multiply(x,y).


import org.junit.Test;    
import static org.junit.Assert.assertEquals;    

public class MyMathTest {    	

@Test  	
 public void testMultiply() {  		
     MyMath m = new MyMath();  		
     assertEquals("Result", 50, tester.m(10, 5));  	
  }  
}
© Lynne Grewe