EasyMock for Java

8,327 views
8,158 views

Published on

Mocking object based on EasyMock library

Published in: Technology
1 Comment
9 Likes
Statistics
Notes
No Downloads
Views
Total views
8,327
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
340
Comments
1
Likes
9
Embeds 0
No embeds

No notes for slide
  • In our case we are heavily dependent upon recipe loading, map loading. How good it would be if in a test we could skip that and test only the required things.
  • No, it’s not making fun of someone else’s code. It’s creating a mock implementation of an object that can be used as a stand-in in testing.This mock object stands-in for an object that collaborates with the object you are testing. The mock replaces domain dependencies with a mock implementations that is only used in testing. For example you might set up a mock database or a mock connection. Even we can mock the broker  . A mock object allows you to set expectations. You set up the values to be passed to and returned by the mock object. The mock object lets you verify that the expectations were met. The mock object can examine the parameters it was passed and verify that it received the expected values.
  • Why engage in Object Mocking? The real object has behaviour that is hard to cause or is non-deterministic. For example you need to make sure the object you are testing handles an exception thrown from a method invoked on another object. Sometimes it is impossible to force the exception to be thrown on the real object, but an exception can be easily thrown from a mock object. The real object is difficult to set up. Often you must manage the state of an object before using it in a test. This can be difficult if not impossible accomplish. Mock objects can make it much easier to setup state especially when testing objects that need to work with a database or network. The real object has (or is) a User Interface. Interaction with a GUI can be especially troublesome. Interacting with a mock object however can be much simpler. Test needs to query the object, but queries are not available. For example you need to determine if a “callback” method was invoked. Since the mock object verifies that each method was invoked as specified we can know that the “callback” was invoked. If you are engaging in Test-First development the real object may not exist. Using a mock object can aid in interface discovery, a mock object serves as a hypothesis of how an object should act.
  • We will have a look of only EasyMock. After the overview will see some examples using EasyMock.
  • EasyMock uses reflection to dynamically create proxies that implement the specified interface at run time. So the generation of the mock object becomes part of your unit test. EasyMock actually generates two objects at runtime, the Mock Object Mock Object which is an implementation of the interface to simulate and the Easy Mock Mock control which has methods for controlling its associated mock.
  • Easy mock allows you to specify the parameters that should be passed to a method when it is invoked on the mock object. Easy mock also allows you to specify the value to be returned from a method invocation. Easymock also allows you to specify the number of times a method should be invoked. You can also specify the number of times a method should expect a parameter or return a parameter. You can also specify that an exception should be thrown. So for example you could specify that the doit method should be called 2 times with the string ABC as a parameter and the string DEF the third time, it should return true the first two times and throw an exception the third. Finally you can use the verify method to make sure everything went as expected.
  • EasyMock generates it’s mocks at runtime so there is no way to modify the behavior other than through the provided methods. This is sufficient in most cases. Another problem may be that EasyMock uses an objects equals method to compare the expected parameter with the one that was passed from the test object. Sometimes, for example in comparing arrays this may not be what you want.
  • We can mock Interface, classes ( even abstract classes). But we cannot mock final classes.
  • I believe that the use of mock objects can really improved our testing capability.
  • EasyMock for Java

    1. 1. Learning art of Mocking by EasyMock Deepak Singhvi
    2. 2. Agenda <ul><li>Goal </li></ul><ul><li>Unit Testing… can be easy or hard </li></ul><ul><li>What’s a Mock? </li></ul><ul><li>Using Mock Objects </li></ul><ul><li>Mock Frameworks </li></ul><ul><li>To Mock or not to </li></ul><ul><li>EasyMock Overview, Features, Drawbacks </li></ul><ul><li>EasyMock in details – by examples </li></ul><ul><li>Conclusion </li></ul>
    3. 3. Goal of Presentation <ul><li>Show how “Mocking Objects” can greatly improve unit testing by facilitating tests that are easier to write and less dependant upon objects outside the test domain </li></ul>
    4. 4. UT is easy when… <ul><li>Unit testing is easy when </li></ul><ul><li>– your code does not depend on any thing </li></ul><ul><li>No database, file system, web service, socket, …dependencies </li></ul><ul><li>– your code can be tested fully in isolation </li></ul><ul><li>– Does not require other classes/components, frameworks, etc. </li></ul><ul><li>You quickly create an object, run some tests, and off you go </li></ul>
    5. 5. But remember UT means Automation <ul><li>But when we talk about unit testing, we mean automated unit testing. </li></ul><ul><li>We need to be able to run tests quickly. </li></ul><ul><li>Run them as many times as we like. </li></ul><ul><li>You certainly don’t want to do either laborious and/or manual setup and teardown. </li></ul><ul><li>You want to check for behavior and ill behavior of dependent code as well. </li></ul>
    6. 6. testing is easy in isolation
    7. 7. testing is harder with dependencies …
    8. 8. … so remove the dependencies (for developer testing)
    9. 9. Topics of Discussion <ul><li>What is Object Mocking? </li></ul><ul><li>Why Mock Objects? </li></ul><ul><li>What tools are available to support Object Mockery </li></ul>
    10. 10. What is Object Mocking? <ul><li>Mock objects simulate (fake) real objects </li></ul><ul><li>Allows for more modular testing </li></ul><ul><li>Creating a mock implementation of an object that can be used as a stand-in in testing </li></ul><ul><li>Records and verifies expectations of calls </li></ul><ul><li>A mock objects allow you to set expectations </li></ul><ul><li>The mock object lets you verify that the expectations were met or not </li></ul><ul><li>Use the same Interface(s) as the real object </li></ul>
    11. 11. Why engage in Object Mocking? <ul><li>The real object has behavior that is hard to cause or is non-deterministic. </li></ul><ul><li>The real object is difficult to set up. </li></ul><ul><li>The real object is slow. </li></ul><ul><li>The real object has (or is ) a UI. </li></ul><ul><li>Test needs to query the object but queries are not available. </li></ul><ul><li>Real objects do not exist ( Team A is working on X and required Y.y from Team B, at the same time team B is working on Y, to start the task of X team A can mock Y.y) </li></ul><ul><li>Can simulate both behavior and ill-behavior ( For e.g. there is a particular ill behavior which can appear only in the field, but we work on simulation and its difficult to get ill-behavior) </li></ul><ul><li>speeds up development of code under test </li></ul>
    12. 12. To Mock or not to? <ul><li>To </li></ul><ul><ul><li>– Mock only code that code under test directly depends on </li></ul></ul><ul><ul><li>– Mock object that is hard to work with </li></ul></ul><ul><ul><li>– Mock object that takes effort to set up </li></ul></ul><ul><ul><li>– Mock object whose behavior is hard to predict </li></ul></ul><ul><ul><li>– Mock object that requires lots of resources </li></ul></ul><ul><ul><li>– Mock objects that are computationally expensive or very slow </li></ul></ul><ul><ul><li>to respond </li></ul></ul><ul><ul><li>– Mock objects that your test needs to verify with </li></ul></ul><ul><li>Not To </li></ul><ul><ul><li>– Do not mock for the sake of mocking, ask if you can eliminate </li></ul></ul><ul><ul><li>the need for mock by refactoring your code </li></ul></ul><ul><ul><li>– Mock your objects but not resources like database, etc. </li></ul></ul><ul><ul><li>– When writing the real code is easier than writing mock </li></ul></ul><ul><ul><li>– Do not mock what will slow down your UT, mocks should be </li></ul></ul><ul><ul><li>used to speed up UT </li></ul></ul>
    13. 13. What tools are available to support Obect Mockery <ul><li>The MockObjects framework </li></ul><ul><li>MockMaker </li></ul><ul><li>JMock </li></ul><ul><li>NMock </li></ul><ul><li>EasyMock (We are interested only in this particular tool) </li></ul>
    14. 14. EasyMock Overview <ul><li>Open source tool available at easymock.org </li></ul><ul><li>Uses reflection to dynamically create proxies that implement the interface at run time </li></ul><ul><li>EasyMock generates two objects the EasyMock Mock Object and the EasyMock Mock Control </li></ul>
    15. 15. EasyMock Features <ul><li>Allows the expected parameter value to be set for each method </li></ul><ul><li>Allows you to set up the value to be returned by each method </li></ul><ul><li>Allows the number of times the method is to be invoked to be specified </li></ul><ul><li>Allows you to specify an exception the a method should throw </li></ul><ul><li>Will verify that everything went as expected </li></ul>
    16. 16. EasyMock Drawbacks <ul><li>EasyMock generates objects on the fly so you can’t add any behaviour </li></ul><ul><li>EasyMock uses the equals method to compare parameters </li></ul>
    17. 17. General <ul><li>Homepage: www.easymock.org </li></ul><ul><li>Lizence: MIT-Lizence </li></ul><ul><ul><li>Open Source </li></ul></ul><ul><ul><li>Very liberal </li></ul></ul><ul><li>1. Version: 2003 </li></ul><ul><li>Latest Version: April 2006 </li></ul>
    18. 18. Installation <ul><li>Download easymock2.2.zip </li></ul><ul><li>Add easymock.jar as library </li></ul><ul><li>Used in Unit-test (JUnit/TestNG) </li></ul>
    19. 19. EasyMock in detail
    20. 20. How to use it <ul><li>To get a Mock Object, we need to </li></ul><ul><li>1) Create a Mock Object for the interface we would like to simulate, </li></ul><ul><li>2) Record the expect ed behavior, </li></ul><ul><li>3) And switch the Mock Object to replay state . </li></ul><ul><li>EasyMock uses a record/replay metaphor for setting expectations. For each object you wish to mock you create a mock object. To indicate an expectation you call the method, with the arguments you expect on the mock. Once you've finished setting expectations you call replay - at which point the mock finishes the recording and is ready to respond to the primary object. Once done you call verify. </li></ul>
    21. 21. Creating A Mock <ul><li>IEnumeration<Short> iEnumIntfMock = </li></ul><ul><li>EasyMock. createMock (EnumeratedAttribute.class); </li></ul>
    22. 22. Expecting A Lot <ul><li>Expect method is called on mock </li></ul><ul><li>Expect sequence of method calls on mock (call createStrictMock()) </li></ul><ul><li>Expect parameters to methods calls on mock </li></ul>
    23. 23. Expect A Call <ul><li>EasyMock. expect (iEnumIntfMock.getNumberOfRows()); </li></ul>
    24. 24. Expect A Return <ul><li>EasyMock. expect (iEnumIntfMock.getNumberOfRows()). andReturn (5); </li></ul>
    25. 25. Replay <ul><li>Prime the pump to walk through expected call sequence </li></ul><ul><li>Provide return values in same sequence </li></ul><ul><li>Listen to usage of call parameters </li></ul>
    26. 26. Replay Kickoff <ul><li>EasyMock. replay (iEnumIntfMock); </li></ul>
    27. 27. <ul><li>Call all functions as you normally would </li></ul><ul><li>Pass in mock where injectable </li></ul><ul><li>Consider how mock can be passed into internal references </li></ul>
    28. 28. Testing <ul><li>int numOfRows = </li></ul><ul><li>iEnumIntfMock.getNumberOfRows (); </li></ul><ul><li>Assert.assertTrue(&quot;Number of rows does not match&quot;, numOfRows > 0); </li></ul>
    29. 29. <ul><li>Verifying </li></ul>
    30. 30. <ul><li>Called after all operations with the mock are done </li></ul><ul><li>Compares the usage to the recording </li></ul>
    31. 31. Verifying <ul><li>EasyMock. verify (iEnumIntfMock); </li></ul>
    32. 32. Nice Mocks <ul><li>Mocks created by EasyMock usually throw an AssertionError for all unexpected method calls. Sometimes you need a mock that nicely returns default values instead of complaining all the time. Mocks created by EasyMock.createNiceMock() return empty values (0, null, or false) for unexpected method calls. </li></ul>
    33. 33. Strict Mocks <ul><li>By default, the order of method calls is not checked by EasyMock. If you need this, you have to create a Strict Mock with EasyMock.createStrictMock(). You can even switch from strict to normal by EasyMock.checkOrder(Object mock, boolean enableOrderCheck). </li></ul>
    34. 34. What about Mocking Classes with EasyMock? <ul><li>So far we've used EasyMock to create mocks for interfaces, but how about mocking classes? </li></ul><ul><li>Is that possible? No. Yes. No. Yes, well, EasyMock itself is capable of mocking interfaces only. </li></ul><ul><li>But there is another project called EasyMock Class Extension that fills this gap. </li></ul><ul><li>Just use the org.easymock. classextension .EasyMock.* methods instead. You may even mock abstract classes. </li></ul><ul><li>Unfortunately (but not surprisingly), you can't mock final classes. </li></ul>
    35. 35. What this means <ul><li>Object Mocking is an invaluable technique for improving the overall quality of your unit tests. </li></ul><ul><li>Help keep design decoupled </li></ul><ul><li>Check code’s usage of another object </li></ul><ul><li>Test code from the inside out </li></ul><ul><li>Make tests run faster </li></ul><ul><li>Make it easier to write code for problematic resources </li></ul><ul><li>Defer having to write a class </li></ul><ul><li>Test components in isolation from the rest of the system </li></ul><ul><li>Promote interface-based design </li></ul><ul><li>Encourage composition over inheritance </li></ul><ul><li>Refine interfaces </li></ul><ul><li>Test unusual, unlikely, and exceptional situations </li></ul>
    36. 36. Quiz Time
    37. 37. <ul><li>Mocking is one of the most popular tool used Agile and Extreme programming methodologies to follow the Test Driven Development </li></ul><ul><li>( popularly known as TDD). </li></ul>
    38. 38. Thank You <ul><li>[email_address] </li></ul>

    ×