Testing – With Mock Objects - Presentation Transcript
Testing – with Mock objects
Emmett Walsh
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
A Solution
• Allow dummy/mock DAO (or other
classes) be injected into class under test
• Provide setters for objects we would like to
mock
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…
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.
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)
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)
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) )
Demo
• FormulaManagerTest.java (currently uses
hand made mocks)
Results
• Code coverage before EasyMock
– Block 64%
– Line 64%
• Code coverage after EasyMock
– Block 100%
– Line 100%
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
0 comments
Post a comment