+ KOTLIN 46 | FUNCTIONAL JAVA 50 | CDI 59 | CAREERS 77 Testing HUNTING DOWN HARD-TO-FIND ERRORS

SEPTEMBER/OCTOBER 2015

AUTOMATED 14 TESTING FOR JAVAFX

JUNIT’S MOST 20 UNDERUSED FEATURES

BUILDING 26 A SELENIUM TEST GRID

ORACLE.COM/JAVAMAGAZINE //table of contents /

14 20 26 32 42 EIGHT GREATLY BUILDING AND STRESS TESTING THINK LIKE UNDERUSED AUTOMATING JAVA EE A TESTER AND TEST JAVAFX APPS FEATURES OF JUNIT A FUNCTIONAL APPLICATIONS GET RID OF QA WITH TESTFX By Mert Çalişkan TEST GRID By Adam Bien By Mark Hrynczak By Bennet Schulz Make your testing a whole By Neil Manvar Identify application server Atlassian represents the Simple JUnit-style testing of JavaFX UIs lot easier with little-used How to assemble a grid configuration problems, bleeding edge in testing: JUnit capabilities. for Selenium testing potential bottlenecks, its developers are required synchronization bugs, to formulate tests before and memory leaks in they code and after. QA is Java EE code. there to help—but not test. Here’s how it’s working.

COVER ART BY I-HUA CHEN

03 46 59 77 From the Editor JVM Languages Java EE Career One of the most effective tools for Kotlin: A Low-Ceremony, Contexts and Dependency More Ideas to Boost defect detection is rarely used due to High-Integration Language Injection: The New Java EE Your Developer Career old prejudices, except by companies By Hadi Hariri Toolbox By Bruno Souza and Edson Yanaga who can’t afford bugs. They all use it. Work with a statically typed, low- By Antonio Goncalves Skills to develop, activities to explore 06 ceremony language that provides More loose coupling with observers, 25 Letters to the Editor first-class functions, nullability interceptors, and decorators Java Proposals of Interest Corrections, questions, and kudos protections, and complete integration with existing Java libraries. 70 JEP 259: Stack-Walking API 07 Architecture 45 Events 50 A First Look at Microservices Functional Programming User Groups Calendar of upcoming Java By Arun Gupta The Virtual JUG conferences and events Functional Programming The latest trend in enterprise computing in Java: Using Collections is microservices. What exactly are they? 80 10 By Venkat Subramaniam 75 Contact Us Java Books Part 2 of our coverage of functional Have a comment? Suggestion? Reviews of books on JavaFX programming explains the code smells Fix This Want to submit an article proposal? and Java EE 7 that can arise from lambda-based Our latest code challenges from Here’s how to do it. the Oracle certification exams functional routines. 01

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 EDITORIAL PUBLISHING Editor in Chief Publisher Andrew Binstock Jennifer Hamilton +1.650.506.3794 Managing Editor Associate Publisher and Audience Claire Breen Development Director Copy Editor Karin Kinnear +1.650.506.1985 20 Years of Karen Perkins Audience Development Manager Section Development Jennifer Kurtz Michelle Kovac ADVERTISING SALES Technical Reviewers Josie Damian +1.626.396.9400 x 200 Stephen Chin, Reza Rahman, Simon Ritter Advertising Sales Assistant Innovation DESIGN Cindy Elhaj +1.626.396.9400 x 201 Senior Creative Director Mailing-List Rentals # Francisco G Delgadillo Contact your sales representative. 1 Development Platform Design Director Richard Merchán RESOURCES Oracle Products Senior Designer +1.800.367.8674 (US/Canada) Arianna Pucherelli Oracle Services Designer +1.888.283.0591 (US) Jaime Ferrand Senior Production Manager Sheila Brennan Production Designer Kathy Cygnarowicz Since 2002 Since 1999 Since 1995

ARTICLE SUBMISSION Since 1996 Since 1998 Since 1996 If you are interested in submitting an article, please e-mail the editors. SUBSCRIPTION INFORMATION Subscriptions are complimentary for qualified individuals who complete the subscription form. MAGAZINE CUSTOMER SERVICE Since 1996 Since 2008 Since 1998 [email protected] Phone +1.847.763.9635 PRIVACY Oracle Publishing allows sharing of its mailing list with selected third parties. If you prefer that your mailing address or e-mail address not be included in this program, contact Customer Service. Since 1999 Since 2001 Since 1996 Since 2012

Copyright © 2015, Oracle and/or its affiliates. All Rights Reserved. No part of this publication may be reprinted or otherwise reproduced without permission from the editors. JAVA MAGAZINE IS PROVIDED ON AN “AS IS” BASIS. ORACLE EXPRESSLY DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ORACLE BE LIABLE FOR ANY DAMAGES OF ANY KIND ARISING FROM YOUR USE OF OR RELIANCE ON ANY INFORMATION PROVIDED HEREIN. The information is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Java Magazine is published bimonthly at no cost to qualified subscribers by Oracle, 500 Oracle Parkway, MS OPL-3A, Redwood City, CA 94065-1600. Digital Publishing by GTxcel 02

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 //from the editor /

BIO

The Unreasonable Effectiveness of Static Analysis It’s easy to run, provably effective, and greatly underused. Why?

here is perhaps no greater peculiarity in the demics study real-life projects, both open source Tprofession of development than the and inside companies, the perception that they are lack of interest in software engineering. This field, disconnected from reality endures. Their utility, which is the empirical, quantitative analysis of however, shows up when a project with unusual software-development techniques, should be the requirements confronts an organization. Suppose cornerstone of the trade. And yet for most devel- after several years of leading various teams at your opment organizations, it remains a closed domain company and delivering projects roughly on time into which they never venture. Even the emerg- and of the desired quality, you’re charged with ing emphasis on metrics and dashboards has not a green-field project that requires a much lower led to curiosity about what thousands of projects level of defects than your organization is accus- tell us about those very numbers. The disregard tomed to. How will you amp up the quality? extends even to the parlance we use: In most This is where software engineering becomes a locales, a “software engineer” is a seasoned pro- crucial resource: You can see which techniques grammer. There is no implication of familiarity deliver lower defect rates and what their impact with software engineering. on productivity has been historically. Informed Part of this neglect is the view that practitioners with this data, you’ll be able to plan how to go are mostly academics. Although those same aca- about reaching the new goals for this project. (In

PHOTOGRAPH BY BOB ADLER/GETTY IMAGES 03

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 //from the editor /

real life, of course, most organi- and to a lesser extent Checkstyle. false positives a decade ago aver- zations just call in consultants.) Commercial tools—such as those aged 10 percent but now are well Were you to perform this from Coverity, Parasoft, Rogue below 3 percent. In commercial inquiry, it might lead to con- Wave Software, and other ven- products, the rate is even lower. sideration of what practices you dors—are significantly more The other perceived drawback could add to existing projects to advanced. They can do magical is that the tools are slow. This raise their overall quality with- things such as data-motion anal- remains true. You typically run out sacrificing productivity. In ysis, which reveals defects that the high-end tools once a day for many—likely in most—cases, are hard to see via other means. the whole project, but always on that additional practice would be For example, this analysis can code about to be checked in. The static analysis of code. Relying show that a given data item can tools can analyze new code by on the work of Capers Jones, one never be null because all paths cross-checking with the database of the most widely experienced that touch it first pass through of artifacts from the most recent analysts of software-engineering another module far afield that whole-project scan. data, static analysis reduces guarantees nonnullness. Or it can Static analysis has an addi- defects in projects by 44 percent find the opposite, that a method tional upside: It’s not disruptive (from an average of 5.0 defects that counts on being passed only to existing site practices. You per unit of functionality to 2.8 prescreened objects can in fact can add it to a testing pipeline defects). Among standard quality be passed a null. Some of these with ease. This aspect and its assurance techniques, only formal tools excel at finding other very remarkable effectiveness make inspections have a higher effec- difficult bugs, such as unwanted it one of the simplest, but unde- tiveness (60 percent). By com- interactions between two servedly underused, ways to parison, test-driven development threads, or the rare case that a improve quality. (TDD) comes in at 37 percent. data item can be read incorrectly These numbers are not additive, due to the design of the Java Andrew Binstock, Editor in Chief of course. Inspections plus static memory model. These are subtle [email protected] analysis don’t deliver 100 percent items that can be hard to locate @platypusguy defect-free code. By the same and costly to fix—and they’re token, static analysis reveals typically not revealed by formal PS: Update on our evolution: problems that inspections and inspections or unit testing. In this issue, you’ll see that we TDD cannot find. Let me explain. The resistance to static analy- updated our fonts to improve Static-analysis tools today fall sis, I believe, stems from a repu- legibility and we’ve begun into roughly two tiers. There are tation built up in its early days of what will be a long-running the open source tools, which in delivering false positives—that series of articles on JVM lan- Java are particularly good. These is, claiming to find a defect where guages. Let me know if you have include FindBugs, PMD, walkmod, in fact none exists. Per Jones, any suggestions. 04

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 SPONSORED CONTENT

Adobe ColdFusion Celebrates 20 Years of Making Complex Coding Tasks Easy

riginally developed by Jeremy Allaire And it can be used to develop pretty much every on security in ColdFusion give enterprises the and JJ Allaire in 1995 to make it easier application required to meet dynamic business confidence and edge to easily adopt the latest for developers to connect simple HTML needs—which is why it is so prevalent in large technologies as they make their digital transitions. pages to a database, ColdFusion has enterprises and government setups. The future roadmap for improvement in the mobile Obeen around almost as long as the web itself and ColdFusion has a fan following in smaller development platform and the addition of social predates many popular web development languages. organizations, too. “When we started out, as [with] any analytics while staying true to the ColdFusion credo A full scripting language—CFML—and an integrated startup, the budget was always short. So we needed of ‘making hard things easy‘ indicate exciting times development environment were added, and a language that allowed us to develop the application for ColdFusion in the coming years.” ColdFusion remains popular with coders for being in a short period of time. ColdFusion dramatically cut a rapid web application down the development cost,” says Sumit Verma, co- Tridib Roy Chowdhury, General Manager and Senior development platform owner at Ten24 Digital Solutions. Director of Products, Adobe that helps them reduce “ColdFusion has clearly stood the test of time,” development time by an says Rakshith Naresh, product manager at ColdFusion. order of magnitude. “One of the reasons why customers keep coming back Adobe ColdFusion Summit 2015 to ColdFusion is the productivity benefit it offers.” (November 9–10, Las Vegas, Nevada) A history of innovation brings together the web application Over two decades ColdFu- Continuing to blaze the trail community. Interact with ColdFusion sion has been at the fore- “There really isn’t a comparison at all between how experts, domain leaders, and peers, front of simplifying all tasks Adobe reacts to our needs versus any of the other and learn about the latest technologies, programmers find tedious software companies that we work with. Basically, and time consuming, such what happens is ColdFusion allows us to change our techniques, and strategies to help you as charts and graphs, PDF market,” quotes Eric Kratz, president at VSR Systems. rapidly build and successfully deliver Tridib Roy Chowdhury, General Manager and generation and manipu- Be it overhauling your company’s HR operations, web applications to market. Explore how Senior Director of Products, Adobe lation, WebSockets and updating your firm’s global intranet, or powering the ColdFusion is driving change and how you many more. Many of the things that seem so obvious world’s busiest electronic storefronts, you can be sure can propel this momentum. to us now were innovative solutions first offered by this 20-year-old will rise to the occasion. Adobe ColdFusion Summit is the largest ColdFusion, allowing developers to create robust, scal- “ColdFusion continues to do well while staying at summit for ColdFusion developers and has able, high-performing, secure web- and mobile-based the forefront of technology. The unique integration had three successful annual installments. applications with minimal effort. with HTML5 along with the end-to-end mobile Each release has built on the previous ones, and development platform and the increased focus ColdFusion has long since gone beyond its “tag- based scripting language” past. Today, ColdFusion can talk to pretty much everything, from legacy COM and CORBA to .NET assemblies and Java classes. For more information, visit adobe.com/coldfusion //letters to the editor /

Casting for long? May/June issue. We will have many How About a Kindle Version? In the article “What’s New in JPA” more similar articles in the future.” The magazine needs to be avail- in the May/June 2015 issue, I saw able in the Kindle format. I don’t in Listing 17 that the author uses Inside the CPU get why people would download a cast to long. But in fact, if the Thank you so much for driving a PDF, or read the same on their code were the magazine in a more techni- phones. It’s too cumbersome. cal direction. The article “Inside Having a Kindle version will get return em.createQuery( the CPU: The Unexpected Effects you 10x the readers. ..., Long.class) of Instruction Execution” (in —Jude Pereira .getSingleResult(); the March/April and July/August MAY/JUNE 2015 issues) is absolutely awesome! Editor Andrew Binstock responds: it would remove the need for the —Yury Pitsichin “In Silicon Valley, at least, most cast. people in tech read magazines on —Josh Toepfer A Paper Version of Java tablets (which, in my opinion, are Magazine? better for reading articles with code). Author Josh Juneau responds: “You I was wondering if there is a For users of tablets, we offer both are correct that we can get rid of the possibility of getting a printed iOS and Android apps. For all others, cast by passing Long.class as the edition of the magazine, at least we offer PDF. We are actively looking second argument to createQuery() through a third-party provider? at expanding our list of distribution on line 6 of the listing. Thanks for After a complete day of work in targets, and the Kindle is at the top of pointing this out.” front of the computer, it’s good that list. However, we don’t expect to to have a print magazine for a be able to provide that upgrade before IoT Coverage change of environment. the end of the year or early next year.” Now that we’re in an IoT-based —Raj Thondepu world, I wish to see articles Contact Us covering the ecosystem of embed- Publisher Jennifer Hamilton We welcome comments, sugges- ded Java for IoT. This includes the responds: “I totally understand tions, grumbles, kudos, article processor, programming, devel- wanting to disconnect and enjoy a proposals, and chocolate chip opment kits, embedded Java, and printed publication. However, Java cookies. All but the last two might so on. Magazine is being published only in be edited for publication. If your —Sam Desd digital format. When I want to read note is private, please indicate a hard-copy version of an article, this in your message. Please write Editor Andrew Binstock responds: I download the PDF and print the to us at [email protected]. “We had a long article on using Java pages in landscape mode using the For other ways to reach us, please for IoT on the Raspberry Pi in the Fit option in Adobe Acrobat Reader.” see the last page of this issue. 06

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 //events /

attended this free commu- GeeCON San Francisco, California nity event where developers OCTOBER 23–24 learn from fellow developers. PRAGUE, CZECH REPUBLIC In addition to technical topics, Join more than 2,000 par- speakers present on software ticipants at GeeCON, which is branding and legal issues. focused on JVM-based tech- nologies with special attention JAX London to dynamic languages such OCTOBER 12–14 as Groovy and Ruby. GeeCON LONDON, ENGLAND participants share experi- JAX London brings Java, JVM, ences about development and enterprise professionals methodologies and craftsman- together for a technology- and ship, enterprise architectures, methodology-packed event. design patterns, distributed Participants get full access to computing, and more. Big Data Con London, which features modern datastores, W-JAX 15 big data architectures based NOVEMBER 2–6 on Hadoop, and advanced data MUNICH, GERMANY JavaOne 2015 OCTOBER 25–29 JavaDay Kharkiv processing techniques. The W-JAX conference cov- SAN FRANCISCO, CALIFORNIA OCTOBER 1 ers current and future aspects JDD Join the single largest gathering of Java KHARKIV, UKRAINE of technologies such as Java, OCTOBER 13–14 developers. From sessions, workshops, Enjoy and learn in a full day Scala, and Android. Also KRAKOW, POLAND labs, and exhibits to keynotes and Birds- of world-class talks. Topics addressed are web applications JDD is a two-day confer- of-a-Feather sessions, learn about the include core JVM platform and techniques, agile development ence for all Java enthusiasts, latest language changes to improve cod- Java SE (Java 8), JVM languages models, and DevOps. who can participate in more ing efficiency. You’ll also learn how to and new programming para- than 30 lectures, workshops, build modern enterprise and server- digms, web development, and J-Fall 2015 interactive trainings, and net- NOVEMBER 5 based applications, create rich and Java enterprise technologies. working opportunities. JDD EDE, NETHERLANDS immersive client-side solutions, build attracts speakers from all over next-generation apps targeting smart Silicon Valley Code Camp The annual Java conference the world and offers lectures devices, and compose sophisticated Java OCTOBER 3–4 organized by the Dutch Java in English. web services and cloud solutions. SAN JOSE, CALIFORNIA User Group (NLJUG) typically Last year, 4,500 people sells out and has outgrown its usual venue. This year, J-Fall PHOTOGRAPH BY WESTEND61/GETTY IMAGES 07

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 //events /

ence, this event is a university Codemotion Spain Apache Hadoop Innovation Summit day of training, workshops, and NOVEMBER 27–28 FEBRUARY 11–12 labs followed by conference days MADRID, SPAIN SAN DIEGO, CALIFORNIA of sessions on software devel- This two-day event draws nearly With presentations from more opment, web, mobile, gaming, 2,000 attendees, represents more than 25 hands-on industry speak- security, methodology, Internet of than 30 communities, and features ers, topics covered will include Things, and cloud. The Decision coding lectures and workshops. MapReduce and Spark, building Makers evening includes discus- Activities for startups, recruiting, privacy-protected data systems, sion of issues related to the IT and networking are included. scalable data curation, best prac- industry in Morocco. tices, and architectural consider- Clojure eXchange 2015 ations for Hadoop applications. QCon San Francisco 2015 DECEMBER 3–4 NOVEMBER 16–20 LONDON, ENGLAND Embedded World 2016 SAN FRANCISCO, CALIFORNIA Meet with the world’s leading FEBRUARY 23–25 A practitioner-driven software experts, learn how to use Clojure NUREMBERG, GERMANY development conference, QCon is with your team, and discuss war The 14th annual gathering of will take place in the CineMec designed for technical team leads, stories with your peers. Both days embedded system developers in Ede. architects, engineering directors, will feature a mixture of talks will explore the latest develop- Devoxx Belgium and project managers who influ- covering various aspects of Clojure ments, define trends, and once NOVEMBER 9–13 ence innovation in their teams. development: from libraries to again present the key areas of ANTWERP, BELGIUM Tracks this year include Taking music, from ClojureScript to data. focus for future developments. By developers for developers, Java to the Next Level and The This is where hardware, software, Groovy and Grails eXchange 2015 this event has 200 speakers and Dark Side of Security. The last two and system development engi- DECEMBER 14–15 3,500 attendees from 40 coun- days are devoted to workshops. neers come together to turn the LONDON, ENGLAND tries. Tracks this year include Java next milestones of the Internet of Codemotion Milan Stay ahead of the curve and hear SE, JVM languages, and server- Things into reality. NOVEMBER 18–21 the 2016 roadmap for Groovy side Java, as well as cloud and big MILAN, ITALY and Grails from core commit- data, mobile, and architecture and Have an upcoming confer- This conference is open to users ters and Groovy authorities security, among others. ence you’d like to add to our of all languages and platforms. It Guillaume Laforge and Graeme listing? Send us a link and a Devoxx Morocco offers full-day workshops on the Rocher. Engage with other lead- description of your event at NOVEMBER 16–18 first two days, followed by key- ing experts and fellow enthusiasts least four months in advance at CASABLANCA, MOROCCO notes and conference sessions. and learn the latest innovations [email protected]. We’ll Formerly the JMaghreb confer- and practices. include as many as space permits.

PHOTOGRAPH BY HENRYK SADURA/GETTY IMAGES 08

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 AOT Compilation Is Coming to Java 8

Excelsior JET 11 will support Java SE 8 and JavaFX 8 on all desktop platforms.

Get Your Early Access Copy Now Registration-Free Download

LICENSEE

LICENSEE // java books /

JAVA EE 7: THE BIG PICTURE By Danny Coward Oracle Press (McGraw-Hill)

For Java SE developers, Java EE Using Java EE from the start a web front end, a logic layer, has long appeared to be a large can facilitate the addition of and a persistence layer. He then tangle of technologies, primarily features, scalability, and even amplifies this content by bring- of interest to enterprise develop- security for many projects. ing in additional technologies, ers. Even though the Enterprise The trouble is how to go from including WebSocket, dependency Edition has vastly improved since Java SE to Java EE without get- injection, security, and so forth. the days of J2EE, it continues to ting overwhelmed by the seem- The explanations start at a be trailed by its early reputation. ing labyrinth of technologies? high level but quickly descend In part, this is because there is That question is precisely what to code. This code is both clear a sense that any development this book addresses. It provides and extensive. This book aims on Java EE requires familiarity an overview of Java EE 7, sys- squarely at developers, rather with many different services that tematically explaining the core than architects or executives, and need to be integrated just-so to technologies—how they work the programmer reader will find create a proper app. These skills and how they fit together. a clear, very well written text. are in addition to the language The author, a principal archi- My only reservation about the skills, which are assumed. For tect of Java EE, presents the book is that it does not cover many developers, this seeming material in the context of a secondary Java EE technologies, complexity has been solved by hypothetical application that such as Java Message Service or just using a standard container would use the core technologies: JavaMail. But these consider- (Tomcat, for instance) and JDBC on the back end for database When we began doing critical book reviews in the May/June issue, needs. Such an approach works we stated that due to possible conflicts of interest, we would not review well enough until the require- books from Oracle Press. However, after securing approval for indepen- ments expand, at which point dent reviews from both Oracle and McGraw-Hill (the publishers of Oracle continuing to organically grow Press books), we begin in this issue to examine two recent titles from that the app with other unintegrated imprint: one we liked a lot and one we did not. —Ed. technologies becomes a path of declining returns. 10

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 //java books /

ations aside, this is an excellent system (not Eclipse’s OSGI) and undertaking a project using the incomplete introduction to the programming introduction to exposes an extensive UI meta- NetBeans platform will have that technology. Java EE 7. —Andrew Binstock phor—which includes a windows kind of background. For those First, let me touch on what manager with multiwindow sup- readers, this book is a godsend. it doesn’t cover, because these port, search capabilities, a wizard The question I’m led to ask is, are crucial gaps: FXML and CSS builder, and so forth. how many such readers could styling. These two technolo- Under this presentation good- there be? I expect it’s a small set, gies, essential elements of any ness is a lot of technology that which makes me admire both serious introduction, are dis- delivers useful services: for exam- the authors and the publisher for missed via this glib line: “[All ple, an entire file-management releasing a nearly 1,000-page vol- the examples in this book] are in layer, which includes goodies such ume on so narrow a topic. But for Java. Therefore, no understand- as a file-status monitor that issues anyone in that group, this volume ing of CSS or FXML is needed.” a message whenever a watched set is the guide to have. —AB The use of FXML and CSS precisely of files is modified; RESTful web to avoid coding details in Java is services; application update ser- apparently lost on the author. vices; and so on. Many other items are not cov- JAVAFX RICH CLIENT PROGRAMMING The explanations of the best ered. The author mentions JavaFX ON THE NETBEANS PLATFORM ways to exploit the NetBeans technologies that he tells readers Gail and Paul Anderson platform are clear, approach- to learn by themselves. However, Addison-Wesley able, and illustrated with useful if you turn to the section entitled examples. The integration with “For Further Study” to do this, you Of all the words in this book’s JavaFX, however, feels somewhat find only a list of books all writ- title, platform most indicates its rougher. Even though JavaFX is ten by this same author not one of true content. This book is not a presented from scratch (presum- which is about JavaFX. tutorial on JavaFX using NetBeans. ably aimed at someone new to the As to the actual content, the Rather, it’s a book about using technology), a beginner would be author is unhelpful. He covers the JavaFX in conjunction with unlikely to be capable of following INTRODUCING JAVAFX 8 easy things in great detail, and NetBeans as a software platform along without getting lost. The PROGRAMMING the hard things are glossed over. for developing desktop applica- ideal reader is proficient with Java By Herbert Schildt There is precious little here that tions. In this sense, NetBeans as and has familiarity with writing Oracle Press (McGraw-Hill) cannot be found in freely available platform corresponds roughly to UIs either in Swing or JavaFX. For tutorials. For serious developers, the Eclipse Rich Client Platform. such a reader, the JavaFX chap- As fun as JavaFX programming Hendrik Ebbers’ Mastering JavaFX That is, it provides the software ters will serve as a review and an is, it is a world unto itself that 8 Controls provides a far better platform on which rich desktop update that enables safe passage requires a good guidebook to introduction to JavaFX; it covers apps can be built. NetBeans pro- to the discussion of NetBeans fea- understand its ins and outs. both CSS and FXML and does not vides its own internal module But instead, this book is a most tures. Fortunately, almost anyone skirt difficult material. —AB 11

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015

Testing: WE’RE ALL IN THIS TOGETHER

etween the pre- and post-agile generations of developers, there is perhaps no greater difference than the role of developers in testing their code. The concept of developers Bwriting tests as they pushed out code was a radical idea that took root and became an essential part of the coding process. Today some companies, such as Atlassian (page 42), are radicalizing this notion even further by moving all the responsibilities for QA to developers and training newly hired programmers from their first day in QA principles and techniques. While agile values set the course in this new direc- tion, it was undoubtedly the advent of JUnit—a fast test framework with intuitive mechanics—that made developer testing a universal reality. Despite JUnit’s ubiquity, most of us, I fear, use only a familiar sub- set of its features and re-create capabilities already available. Our article on useful but underused fea- tures of JUnit (page 20) should help. User interfaces are not as amenable to JUnit and so require specialized tools. For JavaFX, that tool is increasingly TestFX (page 14). For web-based inter- faces, unfortunately, it is clusters of virtual machines exercising hundreds of combinations of browser releases and operating systems (page 26). Whatever your project’s test tools, it is clear that we will not soon return to the days when coding and testing were segregated activities performed by different teams. I’m good with that. —Andrew Binstock ART BY I-HUA CHEN 13

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 //testing / Test JavaFX Apps with TestFX Simple JUnit-style testing of JavaFX UIs

BENNET SCHULZ estFX is an API for testing user interfaces written in Getting Started with Maven TJavaFX. It automates tests for JavaFX applications by Adding TestFX to a Maven build is as simple as adding the BIO simulating user interactions such as button clicks, typ- JUnit dependency. You need to add only the following snippet ing text into a field, and many other interactions done in to your pom.xml file: JavaFX applications. This article starts with a short background on the TestFX framework, so you can get an understanding of what it is org.loadui testFx based on and what its goals are. After that, the article shows 3.1.2 how to get started with TestFX in Maven projects and how to write tests for a sample application. I also discuss limitations of TestFX that you should know about before using it. Initializing a Sample Test Class Version 4.0.x of TestFX is currently in alpha state. Therefore, If you want to write a TestFX test, your test class needs to this article covers the latest stable version, 3.1.2. I presume extend org.loadui.testfx.GuiTest. After that, you have to that you’ve used JavaFX and have a good understanding of how override the getRootNode method. This method has to return it works, including having a familiarity with FXML. the view that is to be tested. In the following snippet, the method returns an FXML view, but it is also possible to return Background a programmatically created Swing-style class as the view. TestFX is based on the well-known unit testing framework JUnit. Like JUnit, it is very simple to learn and easy to use. In public class SampleTest extends GuiTest { TestFX, tests can be written in a similar way to JUnit tests. There are just a few complements developers need to add. For @Override example, TestFX uses Hamcrest matchers on top of JUnit for protected Parent getRootNode() { test assertions. Parent parent = null; try { The benefit of Hamcrest matchers when compared with parent = FXMLLoader.load(getClass() standard JUnit assertions is that you can use natural assertions .getResource("sample.fxml")); and get more-helpful error messages when an assertion fails. return parent; This increases the code quality of tests, and it also reduces the } catch (IOException ex) { complexity of assertions by offering additional options. // ... 14

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 //testing /

} In contrast to other implementations, this calculator shows return parent; all user input in a field, and when the equals (=) button is } clicked, the result is calculated. Other calculators show only // ... the last numeric input and after the = button is clicked, they } show the result without showing intermediate steps. The view of this application is an FXML file created with By extending GuiTest, you also get additional UI test Gluon Scene Builder 8.0.0, and the buttons are styled with methods that simulate user interactions. For example, you CSS using a linear gradient. The more interesting part is have access to methods for finding UI elements, such as but- the corresponding controller. It contains three methods: tons or fields, and methods for clicking buttons, scrolling handleButtonAction, handleRemoveButtonAction, and scrollbars, and so forth. handleCalculationAction. The first two methods are The Sample Application simple. The last one is the method that calculates the result after the = button is clicked. I’ll focus on testing it. The sample application is a calculator based on the GNOME Listing 1 shows the method for calculating the result gcalctool (see Figure 1). It looks like gcalctool and behaves like depending on the user’s input. gcalctool, but it is written in JavaFX (instead of gcalctool’s original language, Vala). Listing 1. @FXML private void handleCalculationAction(ActionEvent e) { String displayText = display.getText(); int textLength = displayText.length(); String result = ""; if (displayText.contains("+")) { int plusIndex = displayText.indexOf("+"); Double a = Double.valueOf( displayText.substring(0, plusIndex)); Double b = Double.valueOf( displayText.substring(plusIndex + 1, textLength)); result = String.valueOf((a + b)); } else if (displayText.contains("x")) { int multiplyIndex = displayText.indexOf("x"); Double a = Double.valueOf( displayText.substring( 0, multiplyIndex)); Double b = Double.valueOf( Figure 1. The view of the sample application 15

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 //testing /

displayText.substring( Logger.getLogger( multiplyIndex + 1, textLength)); CalculatorControllerTest result = String.valueOf((a * b)); .class.getName()) display.setText(result); .log(Level.SEVERE, null, ex); } } return parent; This method multiplies, divides, adds, and so on. At the end } of this method, the calculated result will be set as the text for the field that is shown at the top of the UI. In the next sec- The next step is about initializing the gcalctoolFX.fxml tion, this method is used to introduce how to write tests for view (see Listing 2) that we want to test with this test class. this application using TestFX. This can be done by loading the respective view and returning Some features (such as subtraction, square, curly brackets, it as the result of the getRootNode method of the test class. floating points, and so on) were left out for simplicity’s sake After that initialization step, we can start writing tests for in this tutorial. If you want to have a version of this calculator this test scenario. A TestFX test must follow standard JUnit 4 that has all its features, it is available in the download area conventions, including using the @Test annotation, a public for this issue of Java Magazine. access modifier, and a return type of void. A sample TestFX test is shown in Listing 3. Writing Tests for the Sample Application Let’s write a test that simulates a user who wants to calculate Listing 3. the sum of 1 + 2. The user does this by clicking 1, +, and 2. @Test public void testAddition() { After the user clicks =, the calculator should display the result Button one = find("#one"); of 3 in the field at the top of the UI. Button plus = find("#plus"); To test this scenario with automated tests, first we add the Button two = find("#two"); Maven dependency, as described earlier, and initialize the Button equalSign = find("#equal"); test class (see Listing 2). click(one); Listing 2. click(plus); public class CalculatorControllerTest click(two); extends GuiTest { verifyThat("#display", hasText("1+2")); @Override click(equalSign); protected Parent getRootNode() { verifyThat("#display", hasText("3.0")); Parent p = null; } try { p = FXMLLoader.load(getClass() As you can see in Listing 3, the test is as simple as a plain .getResource("gcalctoolFX.fxml")); JUnit test. Before the test is run, the view will be constructed } catch (IOException ex) { by the getRootNode method in Listing 2. You need only to 16

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 //testing /

find the button you want to click able, and easy to reconstruct. Therefore, it’s important that via a literal by using the find TestFX is a great the assertions be clear so it’s evident what’s wrong with the method, which is provided by framework for code when a failure occurs. In TestFX, Hamcrest matchers extending the GuiTest class. In are helpful, because they provide more-readable assertions. case of an FXML view, the lit- testing JavaFX Listing 4 shows the simplicity of TestFX tests and the usage of eral is the identifier (fx:id) of a applications. It is Hamcrest matchers for verification. UI element. This identifier has simple and intuitive, to be set to use the UI element Listing 4. in a controller class for bindings and beginners can @Test and event handling. This can be learn it quickly. In public void testMultiplication() { done either by setting it in Scene Button two = find("#two"); addition, it offers a Button times = find("#times"); Builder or editing the FXML file clear API that results Button three = find("#three"); itself. When using programmati- Button equalSign = find("#equal"); cally created views, this identi- in understandable fier has to be set with a setId() tests, which facilitates click(two); method call on the UI elements click(times); that are used in test classes. diagnosing the errors click(three); After getting the buttons with that cause test failures. find()calls, the buttons need verifyThat("#display", hasText("2x3")); click(equalSign); to be clicked in this order: 1, +, 2, verifyThat("#display", hasText("6.0")); =. This can be done by using the } click() method. Before clicking the = button, the calcula- tor should display “1+2” in the field. After clicking the = but- The test in Listing 4 expects a value of 6. A bug is simulated ton, the display should change and show “3.0” to indicate the by changing the multiply operation of the controller so that result of the addition. The display text can be verified with it multiplies two operands and spuriously adds “+1” at the verifyThat(), and the expected text should be an argument end of the multiplication. This bug is introduced to show how of the hasText() method call. TestFX deals with errors. Because of this bug, the test fails, Note that TestFX is compatible with the open source JaCoCo and the corresponding stack trace looks like the following: coverage tool and likely with other tools. It recognizes the lines of code that are covered by your TestFX tests, and you testMultiplication(...CalculatorControllerTest) can track the code coverage as you can do with JUnit tests. Time elapsed: 2.434 sec <<< FAILURE! java.lang.AssertionError: Tests That Fail Expected: Node should have label "6.0" but: Label was "7.0" Screenshot saved as Another important part of unit tests is information about /home/…/screenshot1436949687849.png the ones that fail, especially when you are testing user inter- at ...testfx.Assertions faces. Failing tests should be interpretable, understand- 17

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2015 //testing /

.verifyThat(Assertions.java:38) this issue is to use different CSS IDs for every object, which at ...testfx.Assertions means that the same gradient will need to be applied to each .verifyThat(Assertions.java:26) button separately. at . . . Another limitation is that screenshots are taken as full- ... screen screenshots. Instead of showing the UI window only, Caused by: java.lang.AssertionError: Expected: Node should have label "6.0" TestFX grabs the complete screen with all the other opened but: Label was "7.0" windows in the background. In most cases, the opened win- at org.hamcrest.MatcherAssert dows in the background are unimportant for the re-creation .assertThat(MatcherAssert.java:20) of failed tests. They offer too much information and could at org.loadui.testfx.Assertions show private information about testers or developers, for .verifyThat(Assertions.java:33) example. In addition to that, there is currently no enable ... 35 more and disable mode for taking screenshots. Screenshots will be taken for every test that fails. Sometimes this This (abbreviated) stack trace tells us in a very clear way is undesirable. which test failed, in which line, and with which condi- Also, there has been less development activity for TestFX tion, and it also tells us where the corresponding screenshot lately. TestFX 4.0 has been in prerelease development since was saved. 2014. To ensure that there are future releases of this very Limitations useful software, it would be helpful if there were additional active developers. While TestFX is a very helpful project for testing JavaFX apps, it has some limitations you should be aware of. Conclusion One of the major limitations of TestFX is that debugging TestFX is a great framework for testing JavaFX applications. tests written in TestFX is not necessarily easy. TestFX doesn’t It is simple and intuitive, and beginners can learn it quickly. allow mouse movements while running tests. If you are run- In addition, it offers a clear API that results in understand- ning tests in debug mode and you want to check the values able tests, which facilitates diagnosing the errors that cause of variables in the NetBeans view, for example, TestFX won’t test failures. Nevertheless, there are a few limitations, which react on break points, and the test will also abort because of you should keep in mind when using the current release of the mouse movement. TestFX.