Mockito - Lucky Academy

Download Report

Transcript Mockito - Lucky Academy

Mockito
www.luckyacademy.com
Introduction
• What is Mockito?
– Mockito is mocking frame work for Java Objects.
Introduction…
• Why do we need to Mock Objects?
– When an unit of code depended upon object that
will not be available during test or development.
We can create a mock object of it.
Introduction..
• What is Mock Object
– A mock object is a dummy implementation for an
interface or a class in which you define the output
of certain method calls
Mock frameworks
• Mockito
– http://code.google.com/p/mockito/
• jMock
– http://jmock.org/
• EasyMock
– http://easymock.org/
Mockito
• Mockito is a popular mock framework which
can be used in conjunction with JUnit.
Mockito allows you to create and configure
mock objects
Create a Mock Object
• Mockito supports the creation of mock objects
with the static mock() method call. It also
supports the creation of mock objects based
on the @Mock annotation
– mathObj= mock(Math.class); //Create Math
Object
Configuring the mock objects
• You can use when(....).thenReturn(....) can be
used to specify a condition and a return value
for this condition.
– when(mathObj.add(1, 2)).thenReturn(3); //
Configure it to return 3 when arguments passed
are 1,2
Configure Mock Objects to throw
Exceptions
• when(mathObj.div(anyInt(),
eq(0))).thenThrow(new
ArithmeticException()); // Configure it to
return exception when denominator is zero
Verify
• Mockito keeps track of all the method calls
and their parameters to the mock object. You
can use the verify() method on the mock
object to verify that the specified conditions
are met, i.e., that a method has been called
with certain parameters
– //Verify whether add method is tested with
arguments 1,2
– verify(mathObj).add(eq(1), eq(2));
Limitations
• Following constructs cannot be tested
– final classes
– anonymous classes
– primitive types
Resources
• Our Blog
– http://luckyacademy.blogspot.in/2014/09/mockit
o-tutorial-part1.html
• Source Code of Tutorial
– http://www.luckyacademy.com/downloads.html
Citation
I cant take any credit for this, as I have merely gathered information from below references
• http://www.vogella.com/tutorials/Mockito/ar
ticle.html
• http://gojko.net/2009/10/23/mockito-in-sixeasy-examples/