Tag Archives: jmockit

JMockit Quick Tutorial and Revelation

JMockit is a powerful mocking framework in Java that provides extended functionality that goes beyond the capabilities of all other solutions on the market so far. While most mocking frameworks are proxy based and depend on Reflection to hide the dependent behavior, JMockit falls further and deeper with solving some critical problems such as mocking final classes and static methods by using the Instrumentation API presented in Java 5.

The Instrumentation API allows a direct bytecode replacement in the virtual machine via java agents that modify the codebase of the current classes with the one from our mocked representation (either empty stubs or entirely modified behavior). This is a powerful process that could be hardly debugged even with JMockit codebase - just because the whole lifecycle in the JVM is changed with the agents that do the low level modification (basically done with ASM in the mocking framework).

JMockit Components

JMockit toolkit contains 6 important separated components to be used for mocking reasons. They are:

  • JMockit Expectations
  • JMockit Verifications
  • JMockit State Oriented (Mockups)

  • JMockit Coverage

  • JMockit Hibernate Emulation
  • JMockit AOP

The AOP part is the dark power of that century - just like the other mystic words like Cloud or SaaS or Business Component/Entity. It gives some injection abilities in addition to the standard Mocking approach.

The Hibernate Emulation represents some fake mocks to the Hibernate 3 API, which is however still unstable and not ready (after some research on StackOverflow I found few comments from the author himself discussing the ineffectiveness of some parts of the implementation).

It took me few days to find any reasonable documentation, tutorial and/or codebase for starters. The only resources I found usable for intro to jmockit were Dhruba's examples and some other random code snippets around. The tutorial from the Google Code repository starts with business entities and hardcore logic at first place with no details explained from scratch.

Let's find out how Expectations, Verifications and Mockups work. With a dummy demo that shows the usage of all of them at a place.

Sample case

We have a bank system. A person has a name and some amount of money. We have a Bank object that calculates a resulting sum for a person based on some InterestCalculator. The bank has an interest rate and the calculator executes an algorithm to define additional rate based on the sum that a person owns. Pretty much that's our sample scenario and here there are our demo classes:


  2. public class Person {
  3. private String name;
  4. private double currentSum;
  6. public Person() {
  7. super();
  8. }
  9. public Person(String name, double currentSum) {
  10. super();
  11. this.name = name;
  12. this.currentSum = currentSum;
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. // more getters and setters
  18. }


  2. public class Bank {
  3. private double bankInt;
  4. private String name;
  5. private InterestCalculator calc;
  7. public Bank() {
  8. this("Test Bank", 0.15d);
  9. }
  10. public Bank(String name, double bankInt) {
  11. super();
  12. this.name = name;
  13. this.bankInt = bankInt;
  14. }
  16. // count the sum with the interest for a month but after the bank fees
  17. public double getSumAfterInterest(Person p) {
  18. double currentSum = p.getCurrentSum();
  19. double interest = InterestCalculator.getInterest(currentSum);
  21. // count current sum + the interest and keep in mind bank fees
  22. double result = (currentSum + interest) * (1-bankInt);
  24. return result;
  25. }
  26. // get/set methods
  27. // ...
  28. }

Interest Calc

  2. public class InterestCalculator {
  3. // dummy interest counter
  4. // large interest for small sums
  5. public static double getInterest(double sum) {
  6. if(sum < 1000) {
  7. return sum * 0.3;
  8. }
  9. else if(sum >= 1000 && sum < 10000) {
  10. return sum * 0.2;
  11. }
  12. return 0.1;
  13. }
  14. }

We have set a TestNG project with JMockit integration and we want to test our demo without relying on the InterestCalculator. Assuming that this is a class from an external library and we might not have access to him, we will presume three different cases: 

  1. the InterestCalculator is called twice and the result is 200 after the first call and 400 after the second
  2. the InterestCalculator method is called between 0 and 5 times
  3. the InterestCalculator will use a predefined algorithm that we could modify for the given test

Our demo will mock the InterestCalculator but we are going to use the mocked data through the invocations in the Bank class

Two calls - 200/400

Using the Expectations API we expect that 2 calls of the getInterest(...) method would be done and returned values will be 200d and 400d

  2. public void testFlowMockedInterest() {
  3. new Expectations() {
  4. InterestCalculator interest;
  5. {
  6. interest.getInterest(anyDouble); result = 200.0;
  7. interest.getInterest(anyDouble); result = 400.0;
  8. }
  9. };
  11. Person person = new Person("John", 1000);
  12. Bank bank = new Bank("Alpha", 0.2);
  14. Assert.assertTrue(bank.getSumAfterInterest(person) == 960.0);
  15. Assert.assertTrue(bank.getSumAfterInterest(person) == 1120.0);
  16. }

Expectations are strict here - so they will be executed in exactly the same order and any additional call to the mocked object (or missing call) will lead to exception. We could relace it with NonStrictExpectations class to just omit that obligation. Also, we haven't defined our field as @Mocked because this annotation is applied by default in this case (all fields defined in the anonymous class are being mocked).

Number of calls

If we ignore the exact results but we only need to check the number of invocations, we might test that through Verifications.

  2. @Mocked InterestCalculator interest;
  3. @Test(enabled=true)
  4. public void testFlowVerifiedInterest() {
  5. Person person = new Person("John", 1000);
  6. Bank bank = new Bank("Alpha", 0.2);
  8. bank.getSumAfterInterest(person);
  9. bank.getSumAfterInterest(person);
  10. bank.getSumAfterInterest(person);
  11. bank.getSumAfterInterest(person);
  13. new Verifications() {
  14. {
  15. interest.getInterest(anyDouble); minTimes = 0; maxTimes = 5;
  16. }
  17. };
  18. }

Note: for direct mocking we could add the class as a method parameter. However as we have indirect call through the Bank class, we should define a @Mocked declaration which is visible for all test methods. If you have different definitions in other test methods, remove the Mocked class field when executing other tests.

We could also mix the usage of Expectations and Verifications. Just don't repeat the same code in both blocks cause this would lead to ... well, mistake. Anyway, you could define the mocked class in the Expectations block and omit the usage of the class field. There are also three more types of verifications - InOrder, Full and both (FullVerificationsInOrder). 

Specific behavior

Sometimes we need to declare a more complex logic or just to redefine the class we would normally use in an application. This is the chance for creating a class - replacer as a MockUp where we could define our logic:

  2. @Test(enabled=true)
  3. public void testStubbedInterest() {
  4. new MockUp<InterestCalculator>() {
  5. int percentage;
  6. @Mock
  7. public double getInterest(double sum) {
  8. return 0.1 * ++percentage;
  9. // hacky, nah?
  10. // return new Random().nextDouble() * 100;
  11. }
  12. };
  14. Person person = new Person("John", 1000);
  15. Bank bank = new Bank("Alpha", 0.2);
  17. System.out.println(bank.getSumAfterInterest(person));
  18. System.out.println(bank.getSumAfterInterest(person));
  19. System.out.println(bank.getSumAfterInterest(person));
  20. }

Analogically we could mock the Bank class as well by using either Expectations, or Verifications or MockUp when we only expect specific calls, need to check the number of invocations or need to redefine behavior. Try it and see. And here is the demo downloadable (don't forget to set run parameters to enable the jmockit usage and the integration of testng).

Also, check out my JMockit presentation on Slideshare:

del.icio.us Digg DZone Facebook Google Google Reader Magnolia reddit SlashDot Technorati ReadMe.ru Dobavi.com Dao.bg Lubimi.com Ping.bg Pipe.bg Svejo.net Web-bg.com