Mockito - Lucky Academy

download report

Transcript Mockito - Lucky Academy

• What is Mockito?
– Mockito is mocking frame work for Java Objects.
• 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.
• 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
• jMock
• EasyMock
• 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
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
• when(mathObj.div(anyInt(),
ArithmeticException()); // Configure it to
return exception when denominator is zero
• 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));
• Following constructs cannot be tested
– final classes
– anonymous classes
– primitive types
• Our Blog
• Source Code of Tutorial
I cant take any credit for this, as I have merely gathered information from below references