Feed aggregator

Leaner Java Collections With FastUtil

Javalobby Syndicated Feed - Sun, 10-Jan-16 22:34

In response to my recent post Discovering a Trove of Java Primitives Collection Handling on the GNU Trove library, TheAlchemist pointed out some advantages of fastutil over trove: "I much prefer fastutil (http://fastutil.di.unimi.it/), because it's still in active development, has more features, supports large sizes (> 2^32), and has better documentation." Attila-Mihaly Balazs has seconded this: "I second @TheAlchemist's recommendation for fastutil! It's a great library." In this post, I look at fastutil from some of the same perspectives that I previously looked at trove.

The main fastutil page describes fastutil as an extension of the JavaTM Collections Framework that provides "type-specific maps, sets, lists and queues with a small memory footprint and fast access and insertion" along with "big (64-bit) arrays, sets and lists, and fast, practical I/O classes for binary and text files." The license for fastutil is Apache License, Version 2 and the current version of fastutil requires Java 7 or newer. There are currently (as of this writing) "unmaintained" versions of fastutil available for download as well for Java 6 and Java 5 as well.

Categories: Java

An in-depth look at java.util.LinkedList

Javalobby Syndicated Feed - Sun, 10-Jan-16 05:01

Previously, I introduced you to the Linked List data structure. In this article, let's walk through the Collections class LinkedList and compare it to ArrayList.

As the name implies, the Java class LinkedList is called LinkedList because internally it is based on a Doubly Linked List.

Categories: Java

Java is the #1 Language in January 2016

Javalobby Syndicated Feed - Sun, 10-Jan-16 02:36

The latest TIOBE index has Java language moving strongly into the #1 programming language for January 2016. If you’re not familiar with the TIOBE Index, it’s an index that looks at searches on the major search engines, blogs, forums, and Youtube (Did you know Youtube is now the second biggest search engine?) The “Popularity of Programming Language” index uses a slightly different approach, also has Java remaining at the #1 position for January 2016. Both indexes are giving Java over 20% of the market.

The Java Language Into the Future

I’ve read a lot of articles predicting the demise of the Java language. I don’t see that happening anytime soon. The Java language continues to evolve with the times. Java 7 was a fairly boring release. Java 8, however, has a number of exciting features. Java 8 lambdas are a really neat new feature to Java. It’s a feature that is long overdue. But I have to give kudos to the Java team. They did a real nice job of implementing lambdas.

Categories: Java

Transforming Code to Java 8

Javalobby Syndicated Feed - Sat, 09-Jan-16 00:24

The new facilities in Java 8 is about the change the way we write code. Our code will become more expressive and concise. But, exactly how?

Speaker: Dr. Venkat Subramaniam

Categories: Java

Reading a File As It's Being Written

Javalobby Syndicated Feed - Fri, 08-Jan-16 22:31

The below code describes how to read a file when a particular file is actively being written. Here is a full example. For the below example the mentioned file should be existed in the mentioned path else it will throw FileNotFoundException.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadingFileWhileWrite extends Thread {

    boolean running = true;
    BufferedInputStream reader = null;

    public static void main(String[] args) throws FileNotFoundException {
        ReadingFileWhileWrite tw = new ReadingFileWhileWrite();
        tw.reader = new BufferedInputStream(new FileInputStream("TestFile.txt"));
        tw.start();
    }

    public void run() {
        while (running) {
            try {
                if (reader.available() > 0) {
                    System.out.print((char) reader.read());
                } else {
                    try {
                        sleep(500);
                    } catch (InterruptedException ex) {
                        running = false;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


Categories: Java

The Developer Struggle is Real: What Our Family and Friends Think We Do

Javalobby Syndicated Feed - Fri, 08-Jan-16 03:33

Most developers have experienced this at one time or another. Friends or family members can understand occupations like finance, law, or medicine, but ask them to explain what you do, even at a high level, and they are at a loss for words, intimidated by the black magic nature of your work. “Something to do with computers,” they probably say. *sigh*

Its not like programming is any less complicated than a lawyer or a surgeon’s job. In fact, most developers needed way less formal training than those previously mentioned occupations to get started. The problem is that programming, computers, and the internet are still relatively young concepts in society when compared with jobs that have been around for centuries, like banking or medicine.

Categories: Java

How to Use the Executor Framework

Javalobby Syndicated Feed - Fri, 08-Jan-16 01:32

The Executor framework helps to decouple a command submission from command execution.

In the java.util.concurrent package there are three interfaces:

Categories: Java

Robot Framework Tutorial 2016 – Installation

codecentric Blog - Fri, 08-Jan-16 01:06

Preface

Well, if this were a movie then it would probably be called a remake. This is because we have been writing up a – I hope and believe – pretty comprehensive tutorial on the Robot Framework during the last three years. So why start over? There are two main reasons for this:

  1. Even though there are no revolutionary changes in the Robot Framework, it has evolved during this time and that should be reflected in the new series.
  2. And of course we have learned new things and made new experiences with respect to the framework and overall testing approaches. That is also something that will be incorporated into this new guide.

Ok, enough with the preface. Let’s robot :-).

Robot Framework Fast Forward

Let’s take a very quick tour on the Robot Framework. This is important to get a better understanding on the installation procedure of the framework as described in this blog post. Of course I could have pointed to some older posts for this overview, but I would like to have this blog post self-contained.

Here we go:

  • The Robot Framework is implemented in Python.
  • It also provides a Java Standalone JAR release.
  • Testing functionality is implemented in Keywords, which is the central concept for implementing testing functionality.
  • Keywords for a certain topic (e.g. Database Testing) are bundled in so-called Test Libraries. The Robot Framework comes with a set of Standard Test Libraries.
  • New Keywords – and thus new testing functionality – can be written in Python or Java (and other programming languages that will not be covered by this tutorial).
  • In addition it is possible to create new Keywords by combining existing ones. Doing this is a bit like working with an own programming language.
  • The Robot Framework offers excellent reporting functionality and can be easily integrated to Continuous Integration (CI) Environments.

Robot Framework Installation

Evaluating the Installation Type

There are two different ways to install the Robot Framework as can be already seen from the previous chapter. It can be installed in its Python implementation or as a standalone Java JAR. Unfortunately this has some implications that should be considered from the very beginning.

There are more installation types, but those are either quite special like the .NET installation using IronPython or I simply do not want to recommend those from experience. This is true for using Jython to execute the Robot Framework.

Java Standalone JAR
This installation has some really nice advantages. Assuming Java is more often pre-installed than Python (at least on Windows) it is really an easy start by just downloading the fat JAR. Another really nice thing is that the JAR can be put under version control and thus everyone is really always using the exact same version of it. Also no local installations are required this way.

Sounds too good to be true? Unfortunately it is! If you would like to use some of the tools, especially the graphical IDE (RIDE) you need to install Python and the Python version of the Robot Framework anyway. Furthermore it is more complicated to get Python test libraries to use with the standalone JAR. On the other hand – when under version control – that is a task only one member of the team has to do. Using own Keywords written in Java is quite easy this way.

Python Installation
This is kind of the “natural” way of installing the Robot Framework. Everything else was coming later to especially make things easier for the (large) Java community. Of course all Standard Test Libraries can be used this way and also almost all external Test Libraries are available for the Python installation.

On first sight the biggest drawback here is how to use your own Test Libraries written in Java then. There are two possibilities. The first one is to use Jython, which from experience I would strongly discourage you to do. It always has been a pain one way or the other. The second possibility is to make use of the XML-RPC interface the Robot Framework provides. This is a really great way to use Keyword Libraries written entirely in Java with the Python installation. The next part of this series will deal with Keywords and also cover this.

Installation as such is easy as Python covers its own package manager – namely pip – and the Robot Framework and a lot of related tools and test libraries can be easily installed using pip.

Conclusion
It really depends, as much as I hate this phrase. When planning to use RIDE I think I would go for the Python installation, as it is anyway needed then. Otherwise having the test library under version control using the Java JAR is a nice option. Then again the Python version is faster in execution. If you have time to evaluate both installation types for your project that is of course a good thing to do. Otherwise start with the Python installation, you cannot do anything wrong with it in my opinion.

Performing the Installation

Java Standalone JAR
Download the Robot Framework JAR from here. (At the time writing this blog post 3.0 has been the most recent release. Please check for newer ones by browsing this directory.) Store the downloaded JAR to some proper place on your machine. On my Mac I installed this to /usr/local/opt/robotframework. When using Linux or Mac OS I recommend creating a softlink to point to the most recent Robot Framework JAR. This way updates can be done easier as commands used in scripts or documentation can stay unchanged.

ln -s robotframework-3.0.jar robotframework.jar 

Under Windows either just create a copy or you might be able to use a shortcut for this.

You can then execute the Robot Framework by issuing the following command (of course adjusted to your installation directory):

thomasjaspers$ java -jar /usr/local/opt/robotframework/robotframework.jar --version
Robot Framework 3.0 (Jython 2.7.0 on java1.7.0_79) 

Well, that’s it. The Robot Framework is now ready to use with all its Standard Libraries.

Python Installation
A prerequisite for the Python Installation of the Robot Framework is, well, uhm, Python :-). The latest release (3.0 at the time of writing this) is supporting Python 2.7, 3.3 or newer. I was using Python 2.7.11 when writing this blog post. When working with Linux or Mac OS a proper Python installation is probably available out of the box. Windows users can download Python from here and then install it. Test your Python installation by issuing the following command from the command line:

thomasjaspers$ python --version
Python 2.7.11

Note: It is important that Python can be executed without additional path information. Otherwise scripts and documentation will suffer from different installation directories.

Installing and updating the Robot Framework Python Installation can be best done using the Python Packet Manager pip. Pip should be pre-installed if you are using a recent Python installation. Otherwise it can be installed from the before mentioned web site. You can check your pip-installation with the following command:

thomasjaspers$ pip --version
pip 7.1.2 from /usr/local/lib/python2.7/site-packages (python 2.7)

Now we can install the Robot Framework by issuing:

pip install robotframework

As there was already an installation on my machine I cannot show the terminal output ;-), but luckily I can do an upgrade, which is also very simple using pip:

thomasjaspers$ pip install robotframework --upgrade
Collecting robotframework
  Downloading robotframework-3.0.tar.gz (430kB)
    100% |████████████████████████████████| 434kB 589kB/s 
Building wheels for collected packages: robotframework
  Running setup.py bdist_wheel for robotframework
  Stored in directory: /Users/thomasjaspers/Library/Caches/pip/wheels/5c/52/06/c52eb85b0443321cca0229c7e4c483d2d6d2988de3dd510f50
Successfully built robotframework
Installing collected packages: robotframework
  Found existing installation: robotframework 2.9.2
    Uninstalling robotframework-2.9.2:
      Successfully uninstalled robotframework-2.9.2
Successfully installed robotframework-3.0

Afterwards you can execute the Robot Framework as follows:

thomasjaspers$ robot --version
Robot Framework 3.0 (Python 2.7.11 on darwin)

Congratulations to your second installation of the Robot Framework. Of course this one is also containing all Standard Libraries.

Summary & Outlook

This is  probably enough for one blog post on the topic. We have seen two different ways of installing the Robot Framework. Both should be pretty straightforward, even though the Java Standalone Installation is still a bit easier depending on the state of the Python installation on your machine.

But keep in mind that some tools like RIDE will require the Python installation and installing external Test Libraries might be easier this way. Still the JAR installation can be maintained by one or two responsible team members and kept under version control for easy access. This is also a big advantage.

The next blog post in this series will deal with Keywords, which is the central testing concepts of the Robot Framework. Then we will take a look at RIDE and how to install external Test Libraries.

The post Robot Framework Tutorial 2016 – Installation appeared first on codecentric Blog.

Categories: Agile, Java, TDD & BDD

Consider Static Factory Methods Instead of Constructors

Javalobby Syndicated Feed - Thu, 07-Jan-16 22:31

The normal way for a class to allow a client to obtain an instance of itself is to provide a public constructor. There is another technique that should be a part of every programmer’s toolkit. A class can provide a public static factory method, which is simply a static method that returns an instance of the class. Here’s a simple example from Boolean (the boxed primitive class for the primitive type boolean). This method translates a boolean primitive value into a Boolean object reference:

public static Boolean valueOf(boolean b) {
     return b ? Boolean.TRUE : Boolean.FALSE;
}

Note that a static factory method is not the same as the Factory Method pattern from Design Patterns. The static factory method described in this item has no direct equivalent in Design Patterns. A class can provide its clients with static factory methods instead of, or in addition to, constructors. Providing a static factory method instead of a public constructor has both advantages and disadvantages.

Categories: Java

How to Mock, Spy, and Fake Spring Beans

Javalobby Syndicated Feed - Thu, 07-Jan-16 22:31

About a year ago, I wrote a blog post on how to mock Spring Beans. The patterns described there were a little bit invasive to the production code.  As one of the readers Colin correctly pointed out in a comment. Today I'm introducing a better way to spy/mock Spring Beans based on the @Profile annotation. This blog post is going to describe this technique. I used this approach with success at work and also in my side projects.

Note that widespread mocking in your application is often considered as design smell.

Categories: Java

Simple Java SOAP Web Service Using JDK Tools

Javalobby Syndicated Feed - Thu, 07-Jan-16 03:10

The JDK allows us to both publish and consume a web service using some of its tools. The sample service “Hello world” will be responsible for saying hello to the name that I’ll send it to that service. This example also includes creating a client for this service (you can follow the same steps in client to communicate with any service you like).

A. Creating the Service

1. Construct Simple Hello Class

Suppose you have a simple class that receives a string and return another string

Categories: Java

How To Increase PermGenSpace of Eclipse

Javalobby Syndicated Feed - Thu, 07-Jan-16 02:09

If you see java.lang.OutOfMemoryError: PermGen space errors, you need to increase the permanent generation space available to Eclipse.

PermGen is the permanent generation of objects in the VM (Class names, internalized strings, objects that will never get garbage-collected). An easy, if somewhat memory-hungry fix is to enlarge the maximum space for these objects by adding  -XX:MaxPermSize=128M  as an argument to the JVM when starting Eclipse. The recommended way to do this is via your eclipse.ini file.

Categories: Java

Spring Boot Default App Structure and Component Scan

Javalobby Syndicated Feed - Wed, 06-Jan-16 22:08

I’m familiar with the Spring Framework’s concept of a ‘component scan’ to find its managed beans when the app initializes, but I was looking for how to configure the package(s) for the component scan in a Spring Boot app.

Turns out (see docs here), by convention if your main app class is annotated with @SpringBootApplication and is in a package with all your code in packages below this point, then those subpackages are scanned by default.

Categories: Java

Deploying Java EE 7 Apps with WildFly Swarm on Heroku

codecentric Blog - Wed, 06-Jan-16 02:29

With WildFly Swarm there is an new approach to packaging and running Java EE applications. It offers a way to pick single JEE features like JAX-RS, EJBs or even JPA. There is no need to use the whole JEE stack unless you want it.
In addition to that, developers can get rid of the common packages like .war or even .ear files and deploy small far-jars instead. Nevertheless WildFly Swarm is also backward compatible and allows developers to package applications as .war files and deploy it on well known application servers like WildFly, WebSphere or Payara.

swarm_logo

Heroku is a cloud Platform as a Service (PaaS) Provider who supports the following programming languages: Java, Scala, Clojure, Node.js, Go, PHP, Python and Ruby. By using cloud based PaaS you don’t need to install application servers, take care of hardware and network stuff. You can choose between three different versions with different pricing modules:

  • the “Free” version
  • the “Hobby” version
  • and the “Professional” ones.

In this blogpost we will take the Free version, just because we don’t need that power for the WildFly Swarm App. In case you suddenly need more performance you can upgrade and scale it very quickly.
Note: The Free version of Heroku needs to sleep your application if there is no activity within the last 30 minutes and it also must sleep 6 hours in a 24 hours period.

heroku

Getting Started with Heroku

There are some preconditions when deploying applications on Heroku:

  1. You need a (free) Heroku account
  2. Java 8 should be installed locally
  3. Maven 3 should also be installed locally (it’s also possible to use Gradle instead of Maven)

After that you can follow the Heroku Getting Started Guide with Java, which is pretty straightforward. The first step is to install a Toolbelt to get access to the Heroku Command Line Interface (CLI) which is necessary in the next deployment steps.
In the next step

The post Deploying Java EE 7 Apps with WildFly Swarm on Heroku appeared first on codecentric Blog.

Categories: Agile, Java, TDD & BDD

Building an Application with Modern Java Technologies

Javalobby Syndicated Feed - Tue, 05-Jan-16 23:41

Sometimes Java gets a bad rap from Agile software developers who suspect it to be a legacy technology on par with COBOL. I understand that being the most used language on the planet means there must be projects of all shapes and sizes out there, including lots of legacy.

That said, Java and the JVM comprise a huge and vibrant ecosystem producing value in all kind of domains from banking to Android applications and scientific software.

Categories: Java

Programmatic Websocket Endpoints in Java EE 7

Javalobby Syndicated Feed - Tue, 05-Jan-16 23:13

This post briefly demonstrates how to develop and deploy (server and client) websocket endpoints using the programmatic version of the Java Websocket API.

Step #1 - Extend the javax.websocket.Endpoint Class

public class ProgrammaticEchoEnpoint extends Endpoint {

    @Override
    public void onOpen(Session session, EndpointConfig config) {
        System.out.println("Peer " + session.getId() + " connected");
        session.addMessageHandler(new MessageHandler.Whole<String>() {
            @Override
            public void onMessage(String message) {
                try {
                    session.getBasicRemote().sendText("Got message from " + session.getId() + "\n" + message);
                } catch (IOException ex) {
                }
            }
        });
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("Peer " + session.getId() + " disconnected due to " + closeReason.getReasonPhrase());
    }

    @Override
    public void onError(Session session, Throwable error) {
        System.out.println("Error communicating with peer " + session.getId() + ". Detail: "+ error.getMessage());
    }
}

Let’s code the client endpoint as well (using the same set of APIs):

Categories: Java

Resolve OutOfMemoryError With Excel Export in the Apache POI Stream API

Javalobby Syndicated Feed - Tue, 05-Jan-16 22:35

Whenever we try to export a huge excel spreadsheet (for example: around 200,000-300,000 records), most of the time we end up with an OutOfMemoryError:JavaHeapSpace. We also consume more time and processing power to export that much of data. The main reason for this kind of problem is that the prior version of Apache POI (prior to 3.8) does not provide a proper solution for this kind of situation, and I also have other issues with the API design in those versions. I've sometimes faced situations where we couldn't support more than 65000 rows of data during excel exports with prior versions of POI. But with version 3.8 and higher, there are solutions for all these problems.

To resolve the memory issues and performance issues of Excel exports, they have utilized a stream API to design to support large data exports. With the stream API we can flush only few rows of data into memory and the reamining rows can be flushed to the hard memory (permanent memory). In this example, you can easily see how it supports larger datasets. I wrote this utility for supporting almost 200,000 records with one of my applications. I hope it will help many who are in search of this kind of solution. I built this solution with Spring MVC.

Categories: Java

Java Annotated Monthly – January 2016

Javalobby Syndicated Feed - Tue, 05-Jan-16 11:35

As we turn the calendar on the Java Annotated, we predict the year ahead will bring enormous growth for Java. With lambdas and streams now firmly planted in the Java ecosystem, developers are starting to reap the benefits of functional programming and cultivating new breeds of reactive services and applications. As the largest, healthiest programming language in the world, Java is poised to make real headway in 2016 and already promises exciting innovation in runtimes, frameworks, tools and languages. Stay tuned on the Java Annotated and you’ll stay ahead of the latest developments and emerging trends every month, brought to you by JetBrains.

IDEAmug5Java

No other language runs on as many devices as Java. From Sega Genesis to smart homes, and mobile phones to mainframes, Java can be found in surprising places. But while Java is often the leading choice for businesses, it faces increasing pressure from newer languages like Python, and Ruby, which favor productivity over convention. Due to its scale and complexity, Java can be slow to innovate and late to adopt modern language features in manyareas. How Java evolves to these pressures in 2016-2017 will affect the future of Java applications for generations to come.

Categories: Java

Writing Better Tests With JUnit

codecentric Blog - Tue, 05-Jan-16 06:30

TLDR;
Writing readable tests is at least as important as writing readable production code. But the standard JUnit tooling won’t help us. In order to create a readable, maintainable, useful test suite, we need to change our testing habits. The focus must be on behavior, instead of implementation.

If you’re a developer, and you’re even remotely like me, you’re writing tests. Lots of tests. In fact, you write tests for everything: Unit tests to verify your classes do what you intend them to do. Integration tests to check your modules and configurations. Acceptance tests to prove that the system has exactly the features you were asked to implement. UI tests, smoke tests, etc. etc.1

Most of the time, these tests aren’t the actual focus of our development; the system under test (SUT) is. The tests just “happen” along the way. And just because we think so much about the production code, its architecture, method and variable names, even whether to put opening braces on the same line2 or on the next – just because we put so much effort into making that code “great”, we often neglect to apply the same care to our tests. Tests, however, also contain code. Code that contains tremendous value: It represents our knowledge about what the system is supposed to do. It is, in fact, in some ways even more valuable than the production code itself.3

The Value of Test Code

Writing fast, bug-free code is easy, if it’s a) not too complex and b) written once, then never touched again. Of course, if you’re working on anything other than a throw-away mobile game, this is never the case. So in order to keep your code as high quality and maintainable as possible, you need tests. Tests allow you to add new features, without breaking what’s already there. Tests help you to make changes in your architecture, without damaging behavior. Tests enable you to find newly introduced bugs early and with little additional effort. And of course, you knew that already…

But tests also serve another purpose.

Have you ever worked on a team, where you had to integrate a new colleague half-way through the project? Easy, right? Just give her the link to the wiki and a comprehensive list of word documents and UML diagrams, and she’ll be on track in no time… Except for she won’t: Because documentation rots even faster than code without tests. Documentation often remains in its original state, even if the system changes dramatically. I would even dare to say that most documentation is already outdated, the second it is written. And even if your IT architect probably disagrees: UML diagrams say little about what actually happens in a running system, however well they are drawn.

Well-written tests, on the other hand, will tell you all of these things (and more):

  • How to access the API
  • What data is supposed to go in and out
  • What possible variations of an expected behavior exist
  • What kind of exceptions might occur, and what happens if they do
  • How individual parts of the system interact with others
  • Examples of a working system configuration

And last, but most definitely not least:

  • What the customer expects the software to do

The value of tests as a form of living documentation can not be overestimated. Especially on larger-sized or long-running projects, a good test suite will not only help onboarding new team members, but also when revisiting older parts of the code base, when reviewing someone else’s code4, or when looking for the occasional bug that somehow made it through the safety net.5

The problem with JUnit

One of the oldest and arguably most widely used test frameworks around is JUnit, originally written by Kent Beck and Erich Gamma in 1998.
It is the Java version of SUnit, one of the first unit testing frameworks, and the “mother” of the xUnit family. It was written with a very simple, rather technical concept in Mind: Individual test cases, with verifiable test results, organized in test suites. It does not, however, include a manual on how big or small each test case should be. Nor does it provide the means to take care of documentation. With just JUnit’s built-in features, these problems remain elusive, and it is up to the programmer to come up with a solution – or not.

To add to the confusion, many of the IDE plugins supporting JUnit project a very one-dimensional idea of a test case: When you create a class in eclipse or IntelliJ, you are easily directed to tools that create a “matching” test, i.e.: A test class that contains stubs to call each public method on your production class, and optionally includes setUp() and tearDown() methods, which are run before and after each individual test stub, or before and after all of the tests.

For, example, if you had a class like this:

public class MyFancyClass {
  public boolean hasFancyProps() {
    return true;
  }
 
  public void myFancyMethod() {
  }
}

You’d be offered this template JUnit 4 test case:

public class MyFancyClassTest {
  @BeforeClass
  public void setUpClass() throws Exception {
    // run once before any of the tests
  }
 
  @Before
  public void setUp() throws Exception {
    // run before each test
  }
 
  @Test
  public void testHasFancyProps() throws Exception {
    // call the hasFancyProps() getter
  }
 
  @Test
  public void testMyFancyMethod() throws Exception {
    // call the myFancyMethod() method
  }
 
  @After
  public void tearDown() throws Exception {
    // run after each test
  }
 
  @AfterClass
  public void tearDownClass() throws Exception {
    // run once after all tests
  }
}

Why is this not helpful? Because while “provide one test stub for everything in the public API” seems like a smart enough concept, it completely ignores both the fact that any moderately sophisticated class reacts differently within different surroundings (i.e.contexts), and the possibility that someone else might need to read and understand what exactly this test does.

What We Can Do

Above all, obviously, we should always apply the same care to our test code that we do to our production code. That means constant refactoring, removing code duplication, keeping methods short and readable, applying the SOLID principles, using comments only when absolutely necessary, etc.etc.

In addition, there are some measures that apply specifically to testing.

1. Test behavior, not implementation

If we set our testing focus on implementation details (e.g., “did we call this method”, or “did we set this variable value”), we create fragile tests: Any time we change even little things in the production code, the tests will break. We will have to re-evaluate our logic every time: Did it break, because we changed how values are stored? Are the expected values still valid? Do we have to access different methods/variables to get the correct results? In short: Does the test need to be changed, because it no longer checks what we expected it to check? Or did it actually break, because we broke the algorithm?

Just by considering these questions, it should be easy to see that repairing brittle tests requires much additional effort, thus making code changes hard and tedious (not to mention: expensive). What we really expect from a test suite, though, is that it should enable us to change our code, not hinder us from doing it!

To overcome the brittleness we need to change our tactics: Instead of checking implementation, we must focus on behavior. Behavior is, by definition:

[…]the range of actions and mannerisms made by individuals, organisms, systems, or artificial entities in conjunction with themselves or their environment
from Wikipedia

“Range of actions and mannerisms” – this explicitly limits our view to what is observable from the outside. If we refrain from disclosing internals, and phrase our tests accordingly, they should become much more flexible, and enable us to refactor, replace and/or rewrite large parts of the production code without additional effort – a true “safety net” that we can rely on. Once implemented, they should always remain green, unless the behavior changes, and therefore only turn red during refactoring, if we made a mistake.

More recent testing frameworks, which were born in the wake of Behavior Driven Development, such as Ruby’s RSpec, JavaScript’s Jasmine and the like, already have a strong focus on behavior and documentation ingrained: Their syntax allows actual text as a way to describe what is happening, and why. Obviously, JUnit lacks a similar mechanism. But fortunately, we can still borrow some concepts and vocabulary to rephrase our own test methods.

BDD expects requirements to be written in the form of “Given-When-Then” statements, i.e.:

Given a precondition
When a thing happens
Then a result should be observable

This represents the so-called “Triple A” pattern: Arrange the preconditions and inputs, Act on the test object, then Assert the results.

We can easily apply this style to JUnit tests, by simply renaming our test methods in the Given-When-Then syntax:

public class MyFancyClassTest {
  private MyFancyClass sut;
 
  @Test
  public void givenAFreshFancyClass_whenCallingFancyTestMethod_shouldHaveFancyProps() throws Exception { 
    sut = new MyFancyClass(); // precondition
 
    sut.myFancyTestMethod();  // thing happens
 
    assertTrue( sut.hasFancyProps() ); // correct result: true
  }
}

Of course, this quickly leads to very long method names (we’ll fix that soon, I promise), but it enables us to think about our tests in a better way, and we can now describe what the test actually does. Great!
Readability can be improved by extracting the “arrange” and “assert” sequences into individual methods, like so:

public class MyFancyClassTest {
  private MyFancyClass sut;
 
  @Test
  public void givenAFreshFancyClass_whenCallingFancyTestMethod_shouldHaveFancyProps() throws Exception { 
    givenAFreshFancyClass();
 
    sut.myFancyTestMethod();  // thing happens
 
    assertFancyProps();
  }
 
  private void givenAFreshFancyClass() {
    sut = new MyFancyClass(); 
  }
 
  private void assertFancyProps() {
    assertTrue( sut.hasFancyProps() );
  }
}

Not only will this help to understand the test, it also makes its code more reusable: We can structure and group setup procedures by extracting more “given” methods, and we can reuse complex assertions by parameterizing the extracted methods. You’ll also notice that this way of phrasing makes it much easier to come up with the next test to write, when you’re going test-first: After all, we’re simply stating what we expect the class to behave like, given one or more preconditions – that’s not a hard thing to think about, and it can easily be done “before the fact”.

But if you start structuring your tests in this manner, you’ll also notice some effects on your production code: Class method names will be directly related to the expected action they should trigger, getter names will represent expected results. You will write code that produces less side-effects. It will be easier to apply the Single Responsibility Principle, find the right abstractions to use, where to extract or move things around. And you will be able to grasp the meaning of things you wrote last week (or last month) much more quickly than before.

2. Group tests by Context

The preconditions that are required for a specific behavior to occur can be considered its context. In order to keep our tests organized, we should try to make sure that test methods, which focus on behavior within the same context, should be grouped closely together. This helps us to find each individual test, and to understand the behavior of the system as a whole more quickly and easily.

One really good way to do this is by using Stefan Bechtold’s HierarchicalContextRunner. It uses inner classes to structure tests into a tree of contexts, both allowing more fine-grained setUp() and tearDown() methods, and shorter method names, while keeping things readable. Here’s an example:

@RunWith(HierarchicalContextRunner.class)
public class MyFancyClassTest {
  private MyFancyClass sut;
 
  @Before 
  public void setUp() throws Exception {
    // runs before each test, maybe calling static initializers
  }
 
  @Test 
  public void shouldTestSomeBehaviorUnderAnyCircumstances() throws Exception {
    // runs without further context   
  }
 
  public class GivenAFreshFancyClass {
    @Before 
    public void setUp() throws Exception {
      // runs after the outermost setUp() method
      sut = new MyFancyClass(); 
    }
 
    public class WhenCallingFancyTestMethod {
      @Before 
      public void setUp() throws Exception {
        // runs before each test within the context, 
        // after the outermost setUp() 
        // AND the one in GivenAFreshFancyClass
        sut.myFancyTestMethod();
      }
 
      @Test
      public void shouldHaveFancyProps() throws Exception { 
        assertTrue( sut.hasFancyProps() );
      }
    }
 
    public class WhenCallingOtherFancyTestMethod {
      @Before 
      public void setUp() throws Exception {
        // runs before each test within the context, 
        // after the outermost setUp() 
        // AND the one in GivenAFreshFancyClass
        sut.myOtherFancyTestMethod();
      }
 
      @Test
      public void shouldNotHaveFancyProps() throws Exception { 
        assertFalse( sut.hasFancyProps() );
      }
    }
  }
}

Grouping tests this way is very powerful: It reduces the amount of code in setUp() and tearDown() to what’s actually different between contexts, makes method names more readable, removes the need for private helper methods, and even allows for code folding, as well as a tree of test results, e.g. in IntelliJs JUnit Runner window:
Screen Shot 2016-01-04 at 15.55.36
Granted, this sample doesn’t quite capture the extent of how much more readable the tests become. Let me assure you: Especially when you’re working with third party code, and your tests require a lot of mocking and stubbing, you will absolutely love HierarchicalContextRunner.

3. Enforce the Single Assertion Rule

One of the most common test anti-patterns is the “Free Ride”, a.k.a. “Piggyback”: A second assertion “rides along” in an existing test method, rather than prompt the creation of a new test. Not only does this obscure the intention of the test, it also leads to less valuable test results: Why did the test break? Can we tell from one glance, or do we have to check line numbers to figure out which assertion failed?

We should always try to limit each test method to a single assertion. However, this does not necessarily mean there can only be one call to Assert.assertEquals() or the like – we can group several statements that belong together semantically into a single assert method of our own design. This also makes our code more readable, because it assigns meaning to an anonymous block of assert statements, which we might have missed or written a comment for, otherwise.

4. Choose meaningful names

Obviously, we should apply the same care to choosing variable and field names, that we apply to choosing method names. This means we should under any circumstances avoid “empty” names like a, test1, data or the like, and instead try to find names that actually explain the meaning of the things we pass around, such as userWithoutPassword, requestWithoutHeaders, and so on.

This will further eliminate the need for comments, as well as require us to think about when and where we create our test doubles and data containers.

5. Avoid complex configuration

In order to keep our tests fast and snappy, we should try to avoid overly complex or bloated configuration. This applies especially to extensive use of dependency injection frameworks like Spring. Just adding the @RunWith(SpringJUnit4ClassRunner.class) annotation will easily increase execution time for each of your test cases by as much as a second. This may not seem much, but in a large suite with thousands of tests, it adds up to a significant amount of time. Maintaining several configuration files for production and test code also increases the amount of work it takes to implement changes and keep things clean: These configurations often develop a life of their own, where obsolete bean configurations continue to exist, beans exist in different scopes, unexpected side effects are introduced, because several tests “reuse” the same configuration file, etc. etc.

A simple way to get around this problem, at least for unit tests, is to use Mockito‘s @InjectMocks annotation to – well – inject any mocks you have configured into the class under test’s fields. This significantly reduces execution time, compared to using Spring’s JUnit runner, and your mock configuration actually ends up within the test, instead of somewhere else on the class path.

An even better way to do it is to declare dependencies explicitly, i.e. have a dedicated constructor or setter methods that you can call from your tests without having to use a third party framework at all.6

6. Avoid test inheritance, if possible

Having many similar test cases often brings along the question of code reuse. And it is a good one… Shouldn’t we try to avoid duplication? Shouldn’t we make sure to use all the OO goodness at our disposal? After all, copy-pasting code from setUp() is just as bad as copy-pasting production code, isn’t it? Wouldn’t we have to maintain the same code in many places?

However valid these points may be – this is the one case where I would consider it a good idea to forgo DRY in favor of keeping tests as decoupled and independent as possible. If our tests depend on each other, we make it harder and more tedious to change our system. Just think about it: If we wanted to change the class hierarchy of our production code, we might suddenly have to do extensive refactoring of our tests. We don’t want our tests to introduce additional dependencies to our code base – we want them to help us get rid of those!
We can reduce the amount of duplicate code by using other means: We could extract extensive setUp code into helper classes, or use creational patterns to produce our test doubles and data objects, for example.7

Inheritance also makes the tests harder to understand. We will at least have to navigate the class hierarchy to understand what is happening, not to mention all the possible confusion inheritance brings along: Methods may be falsely overridden (see Liskov Substitution Principle), there may be visibility issues, name shadowing, etc.etc.

And finally, inheritance also introduces a bunch of performance problems, specifically when working with JUnit.

As usual, there is an exception, though: If you need to test several concrete implementations of the same abstract class, I would consider it useful to mimic the same inheritance structure in your test code, i.e.: Create an abstract test case to do common setUp and tearDown, and to cover all the functionality of the abstract class, and then extend concrete tests for each implementation class from it.

Wait… That’s all?

Of course not. There are lots of things I didn’t cover in this blog post: Which assertion framework to use, when to use which kind of test double, how to provide readable failure messages, … That’s all very exciting, and I am quite sure there will be at least one more article on testing, soon. Until then, I am very much looking forward to reading your comments and suggestions. :)

Footnotes

  1. There are, of course, many other kinds of tests. But since this post centers around tests that could or should be written with JUnit, I’ll spare you the comprehensive list.
  2. This is not intended to be a post about code style. But you should really, always, no exceptions, put opening braces on the same line. Seriously.
  3. Should you ever lose your entire production code base (in the rather hypothetical event of, say, a strangely selective failure in your versioning system), it is not inconceivable that you will be able to recreate all of it in a very short period of time, if your test coverage is good: By going through the test suite and making all the little red lights go green again, you get a nice step-by-step guide to reimplementing the SUT. You may have guessed it: This doesn’t work the other way around. Extrapolating developers’ intentions and overall system concepts from production code is often tedious and takes a very, very long time.
  4. One of the most practical and efficient ways of keeping your code quality high is peer review. If you’re not doing this already, you want to start now.
  5. You can set breakpoints in your test code and step through the corresponding production code in the debugger. Try that with a UML diagram, I dare you.
  6. I know quite a lot of people who would argue vehemently against creating constructors or accessors “only” for use within tests. I, personally, don’t see anything wrong about creating explicit API that enables a more straightforward configuration. Moreover, there are quite a few people who would argue against relying too much on dependency injection frameworks. I suppose, the truly correct answer is the same as always: It depends™.
  7. This also applies to most of our production code, by the way.

The post Writing Better Tests With JUnit appeared first on codecentric Blog.

Categories: Agile, Java, TDD & BDD

Bootiful Enterprise Applications Powered by Spring Boot and Hosted on Payara Micro

Javalobby Syndicated Feed - Mon, 04-Jan-16 23:28

We have already introduced Spring Boot to Payara Micro, the new fish on the block!, by implementing Spring Boot based RESTful web services and hosted on Payara Micro. While implementing it, we didn’t deal with any of the XML configurations or dependency management needed for the Spring framework with the help of  the Spring Boot.

With this article, we will take it one step further by introducing new modules from Java EE like JPA, JSF and many others. Spring Boot will ease the development yet again for us with its bootstrapping methodology. After building our sample application containing simple user interface and persistency, we will deploy it onto Payara Micro, the application server that offers running Java EE applications on a cluster with a small footprint (~60mb) and directly from the console.

Categories: Java

Thread Slivers eBook at Amazon

Syndicate content