Junit, Mockito, etc.
Written by Yaron.karni@gmail.com
https://www.linkedin.com/in/softwarevangelist/
Goal
• Junit & Spring
• Be familiar with
– Junit
– Mockito
– Powermock
– Hamcrest
Agenda
• Test structure
• Junit and spring
• Mockito stubs
• Mockito behavior
• Power mock with private method
• Power mock with static method
Test developers are the heart of a modern test team.
There was a day when you could get away with
hiring a few people to just use the product and call
that a test team. This is no longer the case. Products
are becoming more complex. The lifespan of
products is increasing. More products are being
created for developers instead of end users. These
have no UI to interact with, so simple exploratory
testing is insufficient. To test complex products,
especially over an extended lifespan, the only viable
solution is test automation. When the product is an
API [library or framework] instead of a user
interface, testing it requires programming. Test
developers are programmers who happen to work on
a test team. It is their job to write software which
executes other software and verifies the results.
http://blogs.msdn.com/b/steverowe/archive/2007/01/16/hiring-great-testers-tester-roles.aspx
Scope of Testing
• Unit testing – smallest piece
• Integrating testing – assembles pieces into
larger unit
Junit & Methodlogy
• DoD – Definition of Done
• JUnit4
• Mostly for Public method (Black Box)
• IT – integration test
Key notes
• Template, Structured your unit test code
• Descriptive and specific, Be Focus
• Positive and negative
• Coverage, Cover API method and error code
• Test data, single, collection, hybrid data with
different state.
Style code for unit testing
• Independent, isolated, and self-contained
modules
• Avoid side effects.
• Do not load data from hard-coded locations
• Name.
• Don't assume order
Test Structure
• Arrange
• Act
• Assert
AAA
Arrange
Act
Assert
Exercise
Mockito
• Junit provide assertion over object state.
• Interaction testing
mockito
GWV
object will result in such way.
the object execute an action.
the object behave as expected.
Mockito Abilities
• Explicit API
• Flexible verification
• Separation of stubbing and verification.
• Annotation
Import Mockito lib
• Allow access to mockito method (when, verify
etc) with out the mockito prefix.
Initializing mocks
• Support of annotation @mock
• MockitoAnnotations.initMocks(testClass);
when
Mock an object
Stub method calls
Stubbing consecutive calls
• Stub with different return value/exception for
the same method call
Callbacks
• Advance stubbing
• Implements behavior depending of method
parameters
Callbacks – cont.
When using throw
Verify
• Mockito trace your stack trace
More examples
Handle void return method
• Use of new pattern
• Success case
• Error Case
ArgumentCaptor
• Capture argument values for further
assertions
Mockito matchers
• Flexible verification or stubbing
• Use of hamcrest lib
• More matchers : eq(),any(), isNull(), isNotNull() anyString()
anyInt(), anyFloat(), anyDouble(), anyBoolean(), anyByte(), anyChar(), refEq() , contains(String substring)
matches(String regex), endsWith(String suffix), startsWith(String prefix), etc…
Custom Matcher – cont.
Exercise
Spy real object
• Sometimes it is much convenient to change
behavior of some real object instead of
creating mock from scratch
• Spy delegate call to the real object – not faked
Spring
• Does not provide comprehensive framework
for it.
• But, spring can work with unit testing env
• Support of ReflectionTestUtils
• ReflectionTestUtils I - reflection-based utility
methods.
• 3 main method :
– setField – set private field with value
– invokeSetterMethod– set setter with value
– public static <T> T invokeMethod(Object
target, String name, Object... args)
Spring & Mockito
• Think you would like to inject mock object to
spring, how to do it ?
Exercise
Mockito is good tool – BUT 
• Mockito does not provide way to fake & test
of :
– Private method
– Final class
– Final method
– Static method
– Direct instantiation problem
– Dependency injection dependent
PowerMock
• Solve all the testing problem.
• Use of powerMock extension for mockito
called : powerMockito
Mocking Static method
Mocking private method
POM definition - Parent
<powermock.version>1.5</powermock.version>
<mockito.version>1.9.5</mockito.version>
Update power mock version – if requried
POM definition - Parent
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-classloading-xstream</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule-agent</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
POM definition – Sub Project
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-classloading-xstream</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule-agent</artifactId>
</dependency>
Exercise
Code
Unit test@Test
@SuppressWarnings("unchecked")
public void testGetByPath_positive() {
// arrange
// mock the private method isConfItemCached
ConfigurationServiceClient configurationServiceClientSpy = PowerMockito.spy(configurationServiceClient);
try {
PowerMockito.doReturn(false).when(configurationServiceClientSpy, "isConfItemCached", anyString());
} catch (Exception e) {
fail(e.toString());
}
// mock the static method
PowerMockito.mockStatic(RemotingUtils.class);
BaseResponse<ConfigurationListDTO> res = configurationServiceClientTestUtil.getResult();
try {
PowerMockito.doReturn(res).when(RemotingUtils.class, "runService", anyString(),
(HttpVerb) Mockito.anyObject(), (BaseRequest<String>) Mockito.anyObject(),
Mockito.any(String.class), Mockito.any(ConfigurationListDTO.class),
(RetryStrategy) Mockito.anyObject());
} catch (Exception e) {
fail(e.toString());
}
String path = configurationServiceClientTestUtil.getPath();
// act
ConfigurationClassMock getByPathResult = configurationServiceClient.getByPath(path,
ConfigurationClassMock.class);
// assert
assertNotNull(getByPathResult);
assertEquals(getByPathResult.getIntVal(), configurationServiceClientTestUtil.getIntVal());
assertEquals(getByPathResult.getStringVal(), configurationServiceClientTestUtil.getStringVal());
assertEquals(getByPathResult.getDateVal(), configurationServiceClientTestUtil.getDateVal());
assertTrue(getByPathResult.isBooleanVal());
}
More features
• Google it
hamcrest
hamcrest
• library of matcher objects
• Mockito use some of the hamcrest matchers.
Use of
• assertThat
Kind of matchers
• Core matchers
• Logical matchers
• Object matchers
• Beans matchers
• Collection matchers
• Number matchers
• Text matchers
Matcher over collection
• array - test an array's elements against an
array of matchers
• hasEntry, hasKey, hasValue - test a map
contains an entry, key or value
• hasItem, hasItems - test a collection contains
elements
• hasItemInArray - test an array contains an
element
Custom matcher
• Extensible lib
• Simple
Hamcrest & junit
Thanks

Junit, mockito, etc

  • 1.
    Junit, Mockito, etc. Writtenby Yaron.karni@gmail.com https://www.linkedin.com/in/softwarevangelist/
  • 3.
    Goal • Junit &Spring • Be familiar with – Junit – Mockito – Powermock – Hamcrest
  • 4.
    Agenda • Test structure •Junit and spring • Mockito stubs • Mockito behavior • Power mock with private method • Power mock with static method
  • 5.
    Test developers arethe heart of a modern test team. There was a day when you could get away with hiring a few people to just use the product and call that a test team. This is no longer the case. Products are becoming more complex. The lifespan of products is increasing. More products are being created for developers instead of end users. These have no UI to interact with, so simple exploratory testing is insufficient. To test complex products, especially over an extended lifespan, the only viable solution is test automation. When the product is an API [library or framework] instead of a user interface, testing it requires programming. Test developers are programmers who happen to work on a test team. It is their job to write software which executes other software and verifies the results. http://blogs.msdn.com/b/steverowe/archive/2007/01/16/hiring-great-testers-tester-roles.aspx
  • 6.
    Scope of Testing •Unit testing – smallest piece • Integrating testing – assembles pieces into larger unit
  • 7.
    Junit & Methodlogy •DoD – Definition of Done • JUnit4 • Mostly for Public method (Black Box) • IT – integration test
  • 8.
    Key notes • Template,Structured your unit test code • Descriptive and specific, Be Focus • Positive and negative • Coverage, Cover API method and error code • Test data, single, collection, hybrid data with different state.
  • 9.
    Style code forunit testing • Independent, isolated, and self-contained modules • Avoid side effects. • Do not load data from hard-coded locations • Name. • Don't assume order
  • 10.
  • 11.
  • 12.
  • 13.
    Mockito • Junit provideassertion over object state. • Interaction testing
  • 14.
  • 15.
    GWV object will resultin such way. the object execute an action. the object behave as expected.
  • 16.
    Mockito Abilities • ExplicitAPI • Flexible verification • Separation of stubbing and verification. • Annotation
  • 17.
    Import Mockito lib •Allow access to mockito method (when, verify etc) with out the mockito prefix.
  • 18.
    Initializing mocks • Supportof annotation @mock • MockitoAnnotations.initMocks(testClass);
  • 19.
  • 20.
  • 21.
  • 22.
    Stubbing consecutive calls •Stub with different return value/exception for the same method call
  • 23.
    Callbacks • Advance stubbing •Implements behavior depending of method parameters
  • 24.
  • 25.
  • 26.
    Verify • Mockito traceyour stack trace
  • 27.
  • 28.
    Handle void returnmethod • Use of new pattern • Success case • Error Case
  • 29.
    ArgumentCaptor • Capture argumentvalues for further assertions
  • 30.
    Mockito matchers • Flexibleverification or stubbing • Use of hamcrest lib • More matchers : eq(),any(), isNull(), isNotNull() anyString() anyInt(), anyFloat(), anyDouble(), anyBoolean(), anyByte(), anyChar(), refEq() , contains(String substring) matches(String regex), endsWith(String suffix), startsWith(String prefix), etc…
  • 31.
  • 32.
  • 33.
    Spy real object •Sometimes it is much convenient to change behavior of some real object instead of creating mock from scratch • Spy delegate call to the real object – not faked
  • 34.
    Spring • Does notprovide comprehensive framework for it. • But, spring can work with unit testing env • Support of ReflectionTestUtils • ReflectionTestUtils I - reflection-based utility methods.
  • 35.
    • 3 mainmethod : – setField – set private field with value – invokeSetterMethod– set setter with value – public static <T> T invokeMethod(Object target, String name, Object... args)
  • 36.
    Spring & Mockito •Think you would like to inject mock object to spring, how to do it ?
  • 37.
  • 38.
    Mockito is goodtool – BUT  • Mockito does not provide way to fake & test of : – Private method – Final class – Final method – Static method – Direct instantiation problem – Dependency injection dependent
  • 39.
    PowerMock • Solve allthe testing problem. • Use of powerMock extension for mockito called : powerMockito
  • 40.
  • 41.
  • 42.
    POM definition -Parent <powermock.version>1.5</powermock.version> <mockito.version>1.9.5</mockito.version> Update power mock version – if requried
  • 43.
    POM definition -Parent <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>${mockito.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4-rule</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-classloading-xstream</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4-rule-agent</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency>
  • 44.
    POM definition –Sub Project <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4-rule</artifactId> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-classloading-xstream</artifactId> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4-rule-agent</artifactId> </dependency>
  • 45.
  • 46.
  • 47.
    Unit test@Test @SuppressWarnings("unchecked") public voidtestGetByPath_positive() { // arrange // mock the private method isConfItemCached ConfigurationServiceClient configurationServiceClientSpy = PowerMockito.spy(configurationServiceClient); try { PowerMockito.doReturn(false).when(configurationServiceClientSpy, "isConfItemCached", anyString()); } catch (Exception e) { fail(e.toString()); } // mock the static method PowerMockito.mockStatic(RemotingUtils.class); BaseResponse<ConfigurationListDTO> res = configurationServiceClientTestUtil.getResult(); try { PowerMockito.doReturn(res).when(RemotingUtils.class, "runService", anyString(), (HttpVerb) Mockito.anyObject(), (BaseRequest<String>) Mockito.anyObject(), Mockito.any(String.class), Mockito.any(ConfigurationListDTO.class), (RetryStrategy) Mockito.anyObject()); } catch (Exception e) { fail(e.toString()); } String path = configurationServiceClientTestUtil.getPath(); // act ConfigurationClassMock getByPathResult = configurationServiceClient.getByPath(path, ConfigurationClassMock.class); // assert assertNotNull(getByPathResult); assertEquals(getByPathResult.getIntVal(), configurationServiceClientTestUtil.getIntVal()); assertEquals(getByPathResult.getStringVal(), configurationServiceClientTestUtil.getStringVal()); assertEquals(getByPathResult.getDateVal(), configurationServiceClientTestUtil.getDateVal()); assertTrue(getByPathResult.isBooleanVal()); }
  • 48.
  • 49.
  • 50.
    hamcrest • library ofmatcher objects • Mockito use some of the hamcrest matchers.
  • 51.
  • 52.
    Kind of matchers •Core matchers • Logical matchers • Object matchers • Beans matchers • Collection matchers • Number matchers • Text matchers
  • 53.
    Matcher over collection •array - test an array's elements against an array of matchers • hasEntry, hasKey, hasValue - test a map contains an entry, key or value • hasItem, hasItems - test a collection contains elements • hasItemInArray - test an array contains an element
  • 54.
  • 55.
  • 56.