JUnit Java Unit Testing

From Kb

Jump to: navigation, search

Contact Article Author | Blog of Article Author | FirstPartners.net Home | LinkedIn profile of Author

See Also

Using EasyMock and JUnit

Outline steps to use JUnit and EasyMock ==

  1. EasyMock allows you to unit test a single class, and have (easy)mock classes handed to it
  2. Setup (either setUp or @Setup) method; create all the classes your that your testing class needs via EasyMock.createMock() method. Java 5 Generics and static imports make this a lot easier
  3. Tell EasyMock what calls should be made out from the class under test to other (in this case mock) classes, and in what order. this is done by calling mock.methodThatShouldBeCalled() in the appropriate order
  4. Switch to activation mode, i.e. call replay(mock)
  5. Run the test again (i.e. call the class / methods under test). Production code will run, and call the mocks collaborators that we have handed to it; any divergence from what should happen is flagged by EasyMock as an AssertionError
  6. Use verify(mock) to ensure that all method have been called when they should have been (previous code just said then when called, the methods were called in the right order)
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
 
public class SomeJunitTest {
 
     private ClassToBeTested m_testObject;
 
     /**
      * Sets up mock objects.
      * the @Tag is important here (Junit4) , not the name of the method
      */
     @Before public void setUpMocks()
     {
          m_testObject= new ClassToBeTested ();
 
          CollaborationClass mockObjectInsteadOfRealDao= createMock(CollaborationClass.class);
          m_testObject.setDao(m_mockObjectInsteadOfRealDao);
 
     }
 
   /**
    * This is Junit4. Junit3 would use testSomething() as a method name
    */
   @Test public void someUnitTest(){
        //'Record' what should happen
        mock.methodThatShouldBeCalledByClassUnitTest("New Document"); // 2 what should happen
 
        //Set to compare actual against would should happen
        replay(mock); // 3
        m_testObject.addDocument("New Document", new byte[0]); 
 
        //make sure we haven't missed any calls that should have been made
        //verify(mock);
    }
Personal tools