Testing – With Mock Objects

3,401 views

Published on

Quick slideshow on using mock objects to test Java managers/facades

Published in: Technology, Business
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,401
On SlideShare
0
From Embeds
0
Number of Embeds
16
Actions
Shares
0
Downloads
106
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Testing – With Mock Objects

  1. 1. Testing – with Mock objects Emmett Walsh
  2. 2. A common problem • Writing a test for a DAO manager – End up writing same test as that for the DAO(s) – Pre-populate DB before tests – Verify DB during/after tests • Not true unit test – more an integration test • If DAO fails , the manager test fails • Would be nice not to have to rely on DB
  3. 3. A Solution • Allow dummy/mock DAO (or other classes) be injected into class under test • Provide setters for objects we would like to mock
  4. 4. Creating Mock objects • Create mock impl of interface that returns ‘fake’ results (i.e. no db access involved) • Or subclass current implementation and override methods • Example…
  5. 5. private class MockFormulaDAO implements IFormulaDAO { public int create(Formula formula, ORDatabaseTransaction transaction) throws DatabaseException { if (formula != null){ //return canned response return 1; } else { throw new NullPointerException(); } } . . . Etc Etc.
  6. 6. Disadvantages • Time consuming • Pollutes code base • More maintenance (e.g. if interface changes) • Much effort involved to add more sophisticated features (e.g. param checking, call order)
  7. 7. Mock frameworks • Mockito • JMock • JMockit (allows mocking of static methods) • Powermock (allows mocking of static methods) • EasyMock
  8. 8. Advantages • Remove the grunt work • Allows to easily simulate collaborators in a test • Offers more features – Order checking of calls to mock object – Param checking in calls to mock object – Can run in various modes (nice v strict) – Mature (Easymock 4yrs, at v2.5.1, lots docs)
  9. 9. EasyMock • Generates mock objects on the fly from interfaces or classes (uses java.lang.reflect.Proxy) • Uses a 4 stage lifecycle – Create mock(s) – Set expectations on the mocks – Put mock(s) in ready mode – Verification of expectations (i.e. the expected methods got called on the mock(s) )
  10. 10. Demo • FormulaManagerTest.java (currently uses hand made mocks)
  11. 11. Results • Code coverage before EasyMock – Block 64% – Line 64% • Code coverage after EasyMock – Block 100% – Line 100%
  12. 12. EasyMock - Conclusion • Helps us write better tests in shorter time • Allows us to possible separate unit tests from integration tests – they run fast! • True unit tests could possibly be run at customer site as a quick sanity check ??? • Easy – low learning curve • Reliable – comes with its own unit tests, 180+ test classes
  13. 13. End

×