Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
All about unit testing using (power) mock
1. All about unit testing
using (power) mock
by Pranalee Rokde
2. Why don’t we write Junit tests?
Invalid reasons
It doesn’t catch bugs
Its slower
Its boring
Hard to change
Too many interfaces
Testing is for QA
Valid reasons
Don’t know how
Legacy code
3. Testing Components
Code to be tested can be broken into 3 parts:
Testing of
1. Public API Methods
2. Static Methods
3. Private Methods
4. 1.Use PowerMockito for Mocking and Mockito for verifying
2. How to Mock:
ClassName instance1 = PowerMockito.mock(ClassName.class);
PowerMockito.when(instance1.method1(arg1)).thenReturn(returnObjectInstance);
3. Verifying
For method behaviour:
Mocktio.Verify(times(1))
Mockito.noMore Interactions
For return values/objects:
Use Assert
Public API Methods
5. Static Methods
1. Use PowerMockito for both mocking and verifying
2. How to Mock:
PowerMockito.mockStatic(ClassWithStaticMethods.class)
PowerMockito.when(ClassWithStaticMethods.staticMethodCall()).thenReturn
(obj1);
3. How to verify:
PowerMockotio.verifystatic(Mockito.times(1));
ClassWithStaticMethods.staticMethodCall()
6. Private Methods - I
There are 2 school of thoughts when it comes to testing of
private methods. We will look at both perspectives.
In first school of thoughts:
1. Private methods should be tested via Public Methods only
2. Private methods Should NOT be mocked while testing
object
3. If private methods are difficult to test,consider refactoring
code
4. Test should not depend on private methods, because
changes like refactoring will break test cases
7. Private Methods - II
Another school of thought says:
1. Private Methods are units of code. So they should be
tested while unit testing
2. Unit tests of private methods helps to zoom in defect
3. How to test - Without having to change your code
1. Invoke private method directly:
Whitebox.invokeMethod(classInstance, "methodname",arg1);
2. To confirm invocations made while calling public methods:
PowerMockito.spy()
8. Emma - Check your code coverage
http://www.eclemma.org/installation.html
9. JUnitGenerator
1. Ideally, test cases should be written at the same time of writing code.
2. But if you have existing code base without Junit coverage
3. This is the utility that I’ve created to generate junit stub for existing classes.
4. Download link
10. Hard to test code
1. New operator everywhere
2. Lots of static methods
3. Singletons
4. Deep class hierarchy
11. Good code
1. Favor composition over inheritance
2. Favor polymorphism over conditionals
3. SRP
4. DRY
5. Avoid object construction with application logic
6. Breakdown code into small testable units
12. Good JUnit Practices
1. Name testing methods more descriptive - preferably use
case driven
2. Testing is better while writing the code
3. Test explicilty for unexpected use cases