Tag Archives: Java

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:

Person

  1.  
  2. public class Person {
  3. private String name;
  4. private double currentSum;
  5.  
  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. }
  19.  

Bank

  1.  
  2. public class Bank {
  3. private double bankInt;
  4. private String name;
  5. private InterestCalculator calc;
  6.  
  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. }
  15.  
  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);
  20.  
  21. // count current sum + the interest and keep in mind bank fees
  22. double result = (currentSum + interest) * (1-bankInt);
  23.  
  24. return result;
  25. }
  26. // get/set methods
  27. // ...
  28. }
  29.  

Interest Calc

  1.  
  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. }
  15.  

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

  1.  
  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. };
  10.  
  11. Person person = new Person("John", 1000);
  12. Bank bank = new Bank("Alpha", 0.2);
  13.  
  14. Assert.assertTrue(bank.getSumAfterInterest(person) == 960.0);
  15. Assert.assertTrue(bank.getSumAfterInterest(person) == 1120.0);
  16. }
  17.  

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.

  1.  
  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);
  7.  
  8. bank.getSumAfterInterest(person);
  9. bank.getSumAfterInterest(person);
  10. bank.getSumAfterInterest(person);
  11. bank.getSumAfterInterest(person);
  12.  
  13. new Verifications() {
  14. {
  15. interest.getInterest(anyDouble); minTimes = 0; maxTimes = 5;
  16. }
  17. };
  18. }
  19.  

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:

  1.  
  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. };
  13.  
  14. Person person = new Person("John", 1000);
  15. Bank bank = new Bank("Alpha", 0.2);
  16.  
  17. System.out.println(bank.getSumAfterInterest(person));
  18. System.out.println(bank.getSumAfterInterest(person));
  19. System.out.println(bank.getSumAfterInterest(person));
  20. }
  21.  

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

Java2Days 2010 – Overview

 This week has been inspired by the power ot Java (this is how a movie like Javatar would probably start).

Offtopic

java2daysAnyway, I'm glad that I attended Java2Days event this year. It's been my second Java2Days event including the one in Oct 2009 (which I described in my Bulgarian blog with auto Google translation in EN). After few years being highly coupled with Java, I decided to do some freelance which lasts for about 2 years now. Meanwhile in addition to Java I've studied plenty of new technologies - PHP and Python in depth, different frameworks down there, few abstract programming structures for specific projects, set-top boxes etc. This makes me feel even more proud being a participant of such an event: now I am able to truly compare scripting languages and Java, dynamic against static typing in different cases - small and medium size projects, enterprise applications, distributed systems. 

Also, as a trainer in different Java-specific trainings (currently Java for QA engineers for VMware and Java EE in the Technical University of Sofia) it's priceless hearing the gossips 'from the back yard' and exploring new features from people being involved in the real process. Thanks to everyone who was passionate enough to talk on topics related to JEE, Spring, Wicket, HTML, mobile techies, Objective-C and others.

Trainers

As always, the Java community presented some of the best shots in the' training industry'. It would be really unbelievable to see Gosling on the stage, but anyway other experienced developers/directors charged the field in the right way (the light way, talking of Java).

The two trainers I was specifically waiting for this year were Andrew Lombardi and Josh Long. These were the guys I enjoyed most last year (including Heath Kesler who couldn't show up this time). Reza Rahman and John Willis also had some great moments for the public. This year all of them did their best one more time - thanks again!

There were also another speakers that I noticed this year. Alexis Pouchkine, Oleg Zhurakousky, Vassil Popovski, Arun Gupta. Eugine Ciurana made a great show 'waking up' the crowd with some jokes and live performance. 

Lectures

Java2Days this year was a mix of 3 conferences - Java2Days, Cloud2Days and MobileDay. Most of the people around (including me) expected Mobile2Days conf with mobile activity the first day, but it turned out that the mobile session is only for the second day.

The focus on Java this year was JEE and the Spring Framework. Scripting languages in the JVM also took part in the 'big three' of the list. Last year there were more presentations on different frameworks from the platform - JSF, GWT, Wicket, Spring and others. I kinda like the flame between different framework evangelists ;)

The introduction Java EE 6 lecture described some of the new features included in the JEE6 (released an year ago). So far every popular application server (and IDE) supports JEE6 fair enough to use it properly. There are noticeable performance improvements, optimizations (code-reducing ones), taking into consideration annotations (instead of the thousand XMLs) and a bit more convention over configuration (which could be a two-sides blade, but most of the time is time saver). 

Long and Zhurakousky presented Spring Integration 2.0 and Intro to Spring. It has been something between a discussion between them both and a stand-up show - Oleg was the sales manager of Spring and Josh was the interested client eager to learn that technology. It was really entertaining, good slides as well and nice overall performance.

Reza presented the DI for JEE - dependency injection was something we could have seen in Spring, but now it's fully supported in JEE (with CID as well). Some demos and real situation examples were demonstrated in this session.

After the lunch break I've been waiting for Andrew's performance. He did another Wicket presentation similar to the one in 2009. This time he recorded a screencast of his creating a Wicket demo. The screencast was recorded during the previous session so it has been almost 'on air' :) Wicket seems a neat framework to try especially if you work closely with designers (who insist on their plain HTML) and need some performance (seems way lighter than JSF for example). Another benefit of the Wicket stuff is the component-oriented architecture, ability for plain URLs (better SEO optimization) and others. Talking with Lombardi during the break we discussed different opportunities to use Wicket in a CMS system. Two existing solutions are Brix and Hippo (both in my testing TODO list).

Vassil Popovski presented the RESTful services topic. As a lead QA manager of VMware he demonstrated REST samples with some testing over there, with plenty of demos creating a bug reporting application. Good performance, real samples, nice work.

Second day I paid less attention due to additional work online and a meeting in the afternoon. Anyway, Gupta did another entertaining demo on Java EE platform as a start.

Eugene joined the sessions for day 2 as a second speaker in Vitosha hall. Gupta is a good speaker, but he's less dynamical and too monotonous for first lecture. Even though topic and demos were fine, all the guys were still sleepy before Eugene. The guy started singing "Who let the dogs out" and made us sing with him (some role singing), which naturally turned attention back to him. He proved himself as the open-source evangelist we've heard him to be. 

At 11:30 we attended the Froyo session in the Mobile hall. I was honestly disappointed on that - as a creator of Android application I expected to hear something meaningful. Despite that after 10 minutes of listening 50% of the attendees left the hall and went to hear another sessions. Nothing useful, nothing Android/Froyo related. 

After that session Emo Abadjiev has presented an interesting presentation named Objective-C for Java developers. Emo was a CEO/CTO of mine in Insight technologies and I have never seen him as a speaker. That's where the pleasant surprise came from - Emo demonstrated great technical and speaking abilities and proved his potential to be a pro trainer. It was really nice to hear his Objective-C story demonstrating his experience with writing for Apple hardware after many years with Java.

The last session I attended was the HTML 5 lecture - again from Andrew Lombardi. Useful theory, plenty of examples, great presentation show, the hall was crowded. That should be descriptive enough. Seems like Andrew was really surprised that there were many people using Opera in there and only 2 of the guys owned Mac machines. Well, pure truth - we still use Opera either on our own, or for testing purposes of web applications. And the Mac machines are usually PCs with Linux/BSDs around, so that's where that all comes from. 

Summary

I would really look forward to attend the next Java2Days here in Bulgaria. I hope that all of the great speakers would return and teach us something new and spicy. Also a good thing to think about is developing the MobileDay into Mobile2Days paying attention to development for Android, iPhone and BlackBerry (three of them has Java APIs to be used). Another interesting topic after the return of the scripting languages is Groovy and Grails with it. VMware are a general sponsor of the event and as they obtain the rights over Groovy, that shall be no that hard.

Another great reviews:

Ivan Ivanov

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

Database training in Switzerland

 

Last week I gave a database training in Switzerland. We had a look into relational databases, normalization theory, some good principles on database modelling, SQL language.

As of the used tools, we had an overview of Oracle 11g free database server, as well as Oracle SQL Developer tool to access the database systems. The E/R diagram toolkit we used to train on was TOAD data modeller. The previous versions of the tool were freeware, but the last implementations available are only evaluation for 2 weeks. You could try to find an old version that does the general work - database drawing, generation of SQL (as well as simple reverse engineering), creation of relations - identifying and non-identifying, as for one-to-one, one-to-many and many-to-many relationships.

In my training here I also extend the presentations with PL/SQL tips and tricks, Object relational mapping with Hibernate and JPA and few practical projects in classes.

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

To summarize technical details for non-professionals

 

I currently lead a course for Database programming with Java and Oracle. This is my third course with that subject, but there is a specific detail here - my trainees are not experienced developers. They are all adult who have experience in different areas - construction engineers, accountants, administrators, scientists. This makes it difficult to present the technology in a way for all of them to understand it correctly.

Except the variety of examples in all of the lectures, I have to decrease the technical level of explanations. I use to speak with less development terms and explain slowly and with an increased attention paid to the students that have less understanding on the subject. I try to combine the visual and audial techniques. I also left my email in order to provide further details on particular topics if there are blur aspects of the technology.

In the beginning of every lecture I summarize the content from the last training. I take notes of the hard parts from the lecture for every student and test his memory and acceptance with practical questions.

It seems to improve the course quality when working with juniors to med developers and have to keep up to a schedule for each subject.

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