Unit testing with mock objects-1 16/7/2009
Agenda What is mocking? Why to use mocking? Types of mocking Easymock Simple Examples of EasyMock(with extensions) and PowerMock
What is mocking? Mocking allows you to test  a class or method  in   isolation  .  A class/method maybe dependent on many other classes/methods. It is with the help of others( collaborators ) a class/method completes itz functionality. In mocking we replace all of its collaborators with  mocks  that essentially  simulate  the normal environment of the class/method. In other words:  “ A mock object is a dummy interface or class in which you define the dummy output of a certain method call.”
Why to use mocking? In mocking we replace all of its collaborators with  mocks DATABASE is not required so NO dbunit Use of Context is avoided Dependencies can be ignored We just test the core functinality of the class/method and we dont have to test the collaborators. Easy,  less time to write  junit for complex legacy code
How Mock Objects Work? 2 Types in general Proxy based like easymock,jmock remap the class file in the class loader like jmockit ,powermock
1. Proxy based Reflection  : Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods  at runtime , without knowing the names of the classes, methods etc. at compile time.  It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.  Using Java Reflection you create dynamic implementations of interfaces at runtime. You do so using the class  java.lang.reflect.Proxy you can set what return values the proxy must return. Proxy is a special class that allows intercept a set of methods identified by an interface  public Object invoke(Object proxy, Method method, Object[] args)
1. Proxy based... a proxy object is used to imitate the real object your code is dependent on.
2. Remap the class file you tell the class loader to remap the reference to the class file it will load.  So let's say that I have a class  Employeee  with the corresponding .class file called  Employeee .class and I want to mock it to use  MyMock  instead.  By using this type of mock objects, you will actually remap in the classloader the reference from  Employeee  to  MyMock .class. Uses the  Instrumentation  API.
What is  EasyMock ? http://easymock.org/ easymock framework helps you create mock objects. Others are :  jmock  /  Mockito  /  rMock   /  jMockit  /  sevenMock
How to use easymock? // Create a mock SomeInterface mock =  createMock  ( SomeInterface.class ); // Record behavior expect ( mock.doStuff( "argument" )).andReturn( "returnValue" ); // Replay behaviour replay ( mock ); // Executing the code we want to test String newValue=test.perform() assume perform() method calls doStuff() method. // Verify behaviour verify (mock);
Step 1 : Create a Mock Identify the classes/methods which are the collaborators.We can mock the classes by first mockin the Interface  createMock  method is used to create the mock object. stmtMock   =  createMock  (  Statement. class  ) ;
Step 2 :  Mock the methods In EasyMock we use a record / replay approach.  record   means -->You first train the mock by making the expected method calls on it . replay  means -->it tells EasyMock to stop recording . After that, it calls on the object to return the set values. If it gets a call it does not expect, it throws an Exception to fail fast. It does not actually replay the mock. BUT it  resets  the mock so that the next time its methods are called it will begin replaying.  st.executeQuery("SELECT * FROM survey"); expect (stmtMock.executeQuery("SELECT * FROM survey")) . andReturn (rsMock);
Step 3 : Execute the code to test AssertEquals  ( 55 ,  idao .getNoOfColumns() );
Step 4 : Verify the behaviour verify  means-->verify( ) method checks to see if the mock actually received  all  the calls you expect The method is used to make sure that all of the behaviour expected from the collaborators is valid.  verify  ( stmtMock );
pom.xml <dependency> <groupId>org.easymock</groupId> <artifactId>easymockclassextension</artifactId> <version>2.4</version> <scope>test</scope> </dependency> <dependency> <groupId>org.easymock</groupId> <artifactId>easymock</artifactId> <version>2.4</version> <scope>test</scope> </dependency>
import import  static  org.easymock.EasyMock.*; import  static  org.easymock.classextension.EasyMock.*;
Syntax To Throw An Exception expect(mock.method()). andThrow (expectedException); Expecting A Method With void Return Type mock.clear(); ExpectLastCall (); Need to mention no. Of calls expectLastCall(). times (3);
Syntax... Argument Matchers  eq (X value) isA (Class clazz) anyBoolean(), anyByte(), anyChar(), anyDouble(), anyFloat(), anyInt(),anyLong(), anyObject(), anyShort()
Drawbacks of easymock Cannot mock static methods Cannot mock private methods Cannot mock final methods Cannot mock concrete classes Cannot mock Constructors jMock does not force us to put expectations on things that are irrelevant to the test at hand. If we're testing Cache.add(), it does not matter what the underlying call to Map.put() returns. With EasyMock, we have to fully specify everything, whether it matters  or not Use  easymock.extensions
Unit testing with mock objects-2
Agenda More about easymock Demo
Types of objects in easymock Normal — createMock():  All of the expected methods must be called with the specified arguments. However, the  order  in which these methods are called  does not matter .  Calls to unexpected methods cause the test to fail. Strict — createStrictMock():  All expected methods must be called with the expected arguments, in a specified order. Calls to unexpected methods cause the test to fail. Nice — createNiceMock():  All expected methods must be called with the specified arguments in any order.  Calls to unexpected methods do not cause   the test to fail.  Nice mocks supply reasonable defaults for methods you don't explicitly mock. Methods that return numbers return 0. Methods that return booleans return false. Methods that return objects return null.
Use of verify The verify phase confirms the execution of the expected calls. Useful in case of strict Mocks,where you need to check whether you called the methods,in right order.It will show all missing method calls. In case of regular mocks it is not necessary.
Repeated calls For every method invoked by the mock we need an expectation. By default mock expects minimum 1 call. times (int min, int max) :  to expect between min and max calls, AtLeastOnce () :  to expect at least one call, and AnyTimes () :  to expected an unrestricted number of calls.
Matchers in EasyMock eq (X value)  :  Matches if the actual value is equals the expected value. Available for all primitive types and for objects. IsNull () :  Matches if the actual value is null. Available for objects. NotNull () :  Matches if the actual value is not null. Available for objects. startsWith (String prefix),  contains (String substring),  endsWith (String suffix) : Matches if the actual value starts with/contains/ends with the given value. Available for Strings. matches (String regex),  find (String regex)  :  Matches if the actual value/a substring of the actual value matches the given regular expression. Available for Strings.

Easymock Tutorial

  • 1.
    Unit testing withmock objects-1 16/7/2009
  • 2.
    Agenda What ismocking? Why to use mocking? Types of mocking Easymock Simple Examples of EasyMock(with extensions) and PowerMock
  • 3.
    What is mocking?Mocking allows you to test a class or method in isolation . A class/method maybe dependent on many other classes/methods. It is with the help of others( collaborators ) a class/method completes itz functionality. In mocking we replace all of its collaborators with mocks that essentially simulate the normal environment of the class/method. In other words: “ A mock object is a dummy interface or class in which you define the dummy output of a certain method call.”
  • 4.
    Why to usemocking? In mocking we replace all of its collaborators with mocks DATABASE is not required so NO dbunit Use of Context is avoided Dependencies can be ignored We just test the core functinality of the class/method and we dont have to test the collaborators. Easy, less time to write junit for complex legacy code
  • 5.
    How Mock ObjectsWork? 2 Types in general Proxy based like easymock,jmock remap the class file in the class loader like jmockit ,powermock
  • 6.
    1. Proxy basedReflection : Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime , without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. Using Java Reflection you create dynamic implementations of interfaces at runtime. You do so using the class java.lang.reflect.Proxy you can set what return values the proxy must return. Proxy is a special class that allows intercept a set of methods identified by an interface public Object invoke(Object proxy, Method method, Object[] args)
  • 7.
    1. Proxy based...a proxy object is used to imitate the real object your code is dependent on.
  • 8.
    2. Remap theclass file you tell the class loader to remap the reference to the class file it will load. So let's say that I have a class Employeee with the corresponding .class file called Employeee .class and I want to mock it to use MyMock instead. By using this type of mock objects, you will actually remap in the classloader the reference from Employeee to MyMock .class. Uses the Instrumentation API.
  • 9.
    What is EasyMock ? http://easymock.org/ easymock framework helps you create mock objects. Others are : jmock / Mockito / rMock / jMockit / sevenMock
  • 10.
    How to useeasymock? // Create a mock SomeInterface mock = createMock ( SomeInterface.class ); // Record behavior expect ( mock.doStuff( &quot;argument&quot; )).andReturn( &quot;returnValue&quot; ); // Replay behaviour replay ( mock ); // Executing the code we want to test String newValue=test.perform() assume perform() method calls doStuff() method. // Verify behaviour verify (mock);
  • 11.
    Step 1 :Create a Mock Identify the classes/methods which are the collaborators.We can mock the classes by first mockin the Interface createMock method is used to create the mock object. stmtMock = createMock ( Statement. class ) ;
  • 12.
    Step 2 : Mock the methods In EasyMock we use a record / replay approach. record means -->You first train the mock by making the expected method calls on it . replay means -->it tells EasyMock to stop recording . After that, it calls on the object to return the set values. If it gets a call it does not expect, it throws an Exception to fail fast. It does not actually replay the mock. BUT it resets the mock so that the next time its methods are called it will begin replaying. st.executeQuery(&quot;SELECT * FROM survey&quot;); expect (stmtMock.executeQuery(&quot;SELECT * FROM survey&quot;)) . andReturn (rsMock);
  • 13.
    Step 3 :Execute the code to test AssertEquals ( 55 , idao .getNoOfColumns() );
  • 14.
    Step 4 :Verify the behaviour verify means-->verify( ) method checks to see if the mock actually received all the calls you expect The method is used to make sure that all of the behaviour expected from the collaborators is valid. verify ( stmtMock );
  • 15.
    pom.xml <dependency> <groupId>org.easymock</groupId><artifactId>easymockclassextension</artifactId> <version>2.4</version> <scope>test</scope> </dependency> <dependency> <groupId>org.easymock</groupId> <artifactId>easymock</artifactId> <version>2.4</version> <scope>test</scope> </dependency>
  • 16.
    import import static org.easymock.EasyMock.*; import static org.easymock.classextension.EasyMock.*;
  • 17.
    Syntax To ThrowAn Exception expect(mock.method()). andThrow (expectedException); Expecting A Method With void Return Type mock.clear(); ExpectLastCall (); Need to mention no. Of calls expectLastCall(). times (3);
  • 18.
    Syntax... Argument Matchers eq (X value) isA (Class clazz) anyBoolean(), anyByte(), anyChar(), anyDouble(), anyFloat(), anyInt(),anyLong(), anyObject(), anyShort()
  • 19.
    Drawbacks of easymockCannot mock static methods Cannot mock private methods Cannot mock final methods Cannot mock concrete classes Cannot mock Constructors jMock does not force us to put expectations on things that are irrelevant to the test at hand. If we're testing Cache.add(), it does not matter what the underlying call to Map.put() returns. With EasyMock, we have to fully specify everything, whether it matters or not Use easymock.extensions
  • 20.
    Unit testing withmock objects-2
  • 21.
    Agenda More abouteasymock Demo
  • 22.
    Types of objectsin easymock Normal — createMock(): All of the expected methods must be called with the specified arguments. However, the order in which these methods are called does not matter . Calls to unexpected methods cause the test to fail. Strict — createStrictMock(): All expected methods must be called with the expected arguments, in a specified order. Calls to unexpected methods cause the test to fail. Nice — createNiceMock(): All expected methods must be called with the specified arguments in any order. Calls to unexpected methods do not cause the test to fail. Nice mocks supply reasonable defaults for methods you don't explicitly mock. Methods that return numbers return 0. Methods that return booleans return false. Methods that return objects return null.
  • 23.
    Use of verifyThe verify phase confirms the execution of the expected calls. Useful in case of strict Mocks,where you need to check whether you called the methods,in right order.It will show all missing method calls. In case of regular mocks it is not necessary.
  • 24.
    Repeated calls Forevery method invoked by the mock we need an expectation. By default mock expects minimum 1 call. times (int min, int max) : to expect between min and max calls, AtLeastOnce () : to expect at least one call, and AnyTimes () : to expected an unrestricted number of calls.
  • 25.
    Matchers in EasyMockeq (X value) : Matches if the actual value is equals the expected value. Available for all primitive types and for objects. IsNull () : Matches if the actual value is null. Available for objects. NotNull () : Matches if the actual value is not null. Available for objects. startsWith (String prefix), contains (String substring), endsWith (String suffix) : Matches if the actual value starts with/contains/ends with the given value. Available for Strings. matches (String regex), find (String regex) : Matches if the actual value/a substring of the actual value matches the given regular expression. Available for Strings.