JUnit Testing using
JMockit
1
What is JMockit ?
• JMockit is a mocking framework available for
unit testing in Java, mainly by using Junit.
• Opensource
• There are many other frameworks present
apart from Jmockit like easyMock,
powerMock, Jmock, Mockito etc.
2
Installation
• Download JMockit jars from www.jmockit.org
• OR you can use Maven to add
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>VERSION NUMBER</version>
</dependency>
Note: It might require <jdk_path>/lib/tools.jar in classpath
3
Installation
Change VM Arguments
Right click on class/project to test click on
RunAs->Run Configurations then change
VM Arguments as shown in the pic
-javaagent:<PATH_TO>/jmockit.jar
4
EXAMPLE
• -
Source : jMockit.org
You can add @Mocked / @Injectable etc in Test Method Arguments too.
5
@Mocked & @Injectable
• @Mocked mocks all the instances of the
specified class.
• Whereas @Injectable mocks the particular
instance specified in the test class.
@Injectable instances should be injected to
the application, so as to be effective.
6
Expectations
Expectations are used to Mock Methods(mainly public, both static and
nonStatic).
Expectations instance is created to return a specific value when a method
from a mocked instance is called.
It follows when then rule (when a.x() method is called then return Y.)
7
Expectations (Cont.)
@Mocked A a;
…
new Expectations{{
a.x(somevalue); returns(Y);
}}
As specified in the previous slide, if you call method x of a
mocked class, then it will return Y(which should be an
object/literal with the return type of method x)
Note : This should appear before your method to test is
called.
8
Expectations(Cont.)
For example, the below example shows how
expectations work.
All instances externalContext,
httpServletRequest and httpSession objects
were mocked.
9
We can use anyString instead of “user”, it will return “Angad” for every string.
Similarly, there are anyInt, anyBoolean, any (for objects), anyDouble etc.
Expectations(Cont.)
Note : Expectations should occur at least once,
or else it will through “missing invocation” error.
If you wish to use strict ordering of the
execution of methods then you can use
StrictExpectations.
10
Partial Mocking or Mocking Methods
If you wish to mock a method of any class, you
can create MockUp<T>() instance. You can
replace the entire code of that method and
rewrite it using MockUp instance.
Note : This should appear before your method
to test is called.
11
Partial Mocking or Mocking Methods
For example. If I want to mock private method getEndpoint(int) of ServiceUtility class. We can use this
code :
new MockUp<ServiceUtility>(){
@Mock
String getEndpoint(int intValue)
{
if(intValue==1)
return “ http://angadrajput.wordpress.com “;
else
return “”;
}
}
Using this you can achieve most of the things that you can do using Expectations, furthermore it is not
necessary to mock
12
Mocking Constructor
Use $init() to mock the Service Utility Class. You can pass
any parameter inside the init method.
new MockUp<ServiceUtility>(){
@Mock
public void $init() {
//YOUR CODE
}
}
13
Setting class fields using JMockit
There can be situations when you need some object but was always Null, because it
might be created from the container classes.
We can instantiate fields using JMockit $init method.
We have to use Invocation and Deencapsulation classes for this as specified below.
new MockUp<ServiceUtility>() {
@Mock
public void $init(Invocation inv){
ServiceUtility utility= inv.getInvokedInstance();
Deencapsulation.setField(utility, “client", new ServiceClient());
//client is a fieldname of the class ServiceUtility
}
};
14
Verifications
What if you wish to test if the method is executed for n times.
It should appear after the tests are executed.
new Verifications() {{
// Verifies the occurrence of at least one invocation
mock1.expectedMethod(anyInt);
// Verifies the occurrence of at exactly two invocation
mock2.anotherExpectedMethod(1, "test"); times = 2;
//You can use minTimes and maxTimes
}};
15
Verifications are by default not in order, i.e. it
will not check the order of execution. Incase you
wish to check methods execution in ordered
sequence, use VerificationsInOrder Class.
If you wish to verify even after the failure of the
test you can use FullVerifications Class.
Verifications(Cont. )
16
JMockit Coverage
Just include jmockit coverage jar. Jmockit will
automatically create an HTML Coverage report
inside your project folder, after each execution
of your testcase.
The path will be specified in the console. Open
index.html to view the coverage report.
17
What to do when ?
Public(static or non static) method of the mocked object is to be called ?
->Use new Expectations(){{ }} instance.
Private(static or non static) method is to be mocked ?
->Use new MockUp<Class>()
When my private field is null and there are no setters?
->Use Constructor mocking with $init() and setting all the fields using Invocation and
Deencapsulation class
Only one method is to be mocked, without mocking the entire class?
->Use new MockUp<Class>()
Constructor is to be mocked?
->Use Contructor mocking using $init()
18
Thank You
Thank you for following my slides, for any
doubts follow http://www.jmockit.org/, or you
can mail me at getangad@gmail.com
-Angad
19

JMockit

  • 1.
  • 2.
    What is JMockit? • JMockit is a mocking framework available for unit testing in Java, mainly by using Junit. • Opensource • There are many other frameworks present apart from Jmockit like easyMock, powerMock, Jmock, Mockito etc. 2
  • 3.
    Installation • Download JMockitjars from www.jmockit.org • OR you can use Maven to add <dependency> <groupId>org.jmockit</groupId> <artifactId>jmockit</artifactId> <version>VERSION NUMBER</version> </dependency> Note: It might require <jdk_path>/lib/tools.jar in classpath 3
  • 4.
    Installation Change VM Arguments Rightclick on class/project to test click on RunAs->Run Configurations then change VM Arguments as shown in the pic -javaagent:<PATH_TO>/jmockit.jar 4
  • 5.
    EXAMPLE • - Source :jMockit.org You can add @Mocked / @Injectable etc in Test Method Arguments too. 5
  • 6.
    @Mocked & @Injectable •@Mocked mocks all the instances of the specified class. • Whereas @Injectable mocks the particular instance specified in the test class. @Injectable instances should be injected to the application, so as to be effective. 6
  • 7.
    Expectations Expectations are usedto Mock Methods(mainly public, both static and nonStatic). Expectations instance is created to return a specific value when a method from a mocked instance is called. It follows when then rule (when a.x() method is called then return Y.) 7
  • 8.
    Expectations (Cont.) @Mocked Aa; … new Expectations{{ a.x(somevalue); returns(Y); }} As specified in the previous slide, if you call method x of a mocked class, then it will return Y(which should be an object/literal with the return type of method x) Note : This should appear before your method to test is called. 8
  • 9.
    Expectations(Cont.) For example, thebelow example shows how expectations work. All instances externalContext, httpServletRequest and httpSession objects were mocked. 9 We can use anyString instead of “user”, it will return “Angad” for every string. Similarly, there are anyInt, anyBoolean, any (for objects), anyDouble etc.
  • 10.
    Expectations(Cont.) Note : Expectationsshould occur at least once, or else it will through “missing invocation” error. If you wish to use strict ordering of the execution of methods then you can use StrictExpectations. 10
  • 11.
    Partial Mocking orMocking Methods If you wish to mock a method of any class, you can create MockUp<T>() instance. You can replace the entire code of that method and rewrite it using MockUp instance. Note : This should appear before your method to test is called. 11
  • 12.
    Partial Mocking orMocking Methods For example. If I want to mock private method getEndpoint(int) of ServiceUtility class. We can use this code : new MockUp<ServiceUtility>(){ @Mock String getEndpoint(int intValue) { if(intValue==1) return “ http://angadrajput.wordpress.com “; else return “”; } } Using this you can achieve most of the things that you can do using Expectations, furthermore it is not necessary to mock 12
  • 13.
    Mocking Constructor Use $init()to mock the Service Utility Class. You can pass any parameter inside the init method. new MockUp<ServiceUtility>(){ @Mock public void $init() { //YOUR CODE } } 13
  • 14.
    Setting class fieldsusing JMockit There can be situations when you need some object but was always Null, because it might be created from the container classes. We can instantiate fields using JMockit $init method. We have to use Invocation and Deencapsulation classes for this as specified below. new MockUp<ServiceUtility>() { @Mock public void $init(Invocation inv){ ServiceUtility utility= inv.getInvokedInstance(); Deencapsulation.setField(utility, “client", new ServiceClient()); //client is a fieldname of the class ServiceUtility } }; 14
  • 15.
    Verifications What if youwish to test if the method is executed for n times. It should appear after the tests are executed. new Verifications() {{ // Verifies the occurrence of at least one invocation mock1.expectedMethod(anyInt); // Verifies the occurrence of at exactly two invocation mock2.anotherExpectedMethod(1, "test"); times = 2; //You can use minTimes and maxTimes }}; 15
  • 16.
    Verifications are bydefault not in order, i.e. it will not check the order of execution. Incase you wish to check methods execution in ordered sequence, use VerificationsInOrder Class. If you wish to verify even after the failure of the test you can use FullVerifications Class. Verifications(Cont. ) 16
  • 17.
    JMockit Coverage Just includejmockit coverage jar. Jmockit will automatically create an HTML Coverage report inside your project folder, after each execution of your testcase. The path will be specified in the console. Open index.html to view the coverage report. 17
  • 18.
    What to dowhen ? Public(static or non static) method of the mocked object is to be called ? ->Use new Expectations(){{ }} instance. Private(static or non static) method is to be mocked ? ->Use new MockUp<Class>() When my private field is null and there are no setters? ->Use Constructor mocking with $init() and setting all the fields using Invocation and Deencapsulation class Only one method is to be mocked, without mocking the entire class? ->Use new MockUp<Class>() Constructor is to be mocked? ->Use Contructor mocking using $init() 18
  • 19.
    Thank You Thank youfor following my slides, for any doubts follow http://www.jmockit.org/, or you can mail me at getangad@gmail.com -Angad 19