Articles in category Java
AssertJ is a great assertion framework for Java. It is in my opinion much better than any of the available alternatives. Two areas where AssertJ shines are verifying collections and verifying exceptions. It is also extendable, so you can implement custom assertions for your domain objects.
The way to assert something is done using the method assertThat(). A typical example looks like this:
assertThat(actual).isEqualTo(expected);
isEqualTo() is overloaded and can be used for a lot of comparisons.
When testing a rest service behind https, you must be able to create a client that supports an encrypted connection.
The trick is to create a javax.ws.rs.client.Client and set the sslContext as well as
the hostnameVerifier() properly.
To support ever shorter release cycles you need to automate testing, and to do that, you need to use a program that can verify your desired behavior. One option is to use tools that can record and replay a scenario, but those are a nightmare to maintain, and you'll probably end up writing the code needed for automating the tests yourself.
For automating the testing of a web application, Selenium is a better way. It takes some programming skills, however, and you must take care to ensure that your tests are easy to understand and maintainable.
Writing maintainable, easy to understand tests might seem hard, but not if you follow these four, simple rules of design.
Read more →A lot of people want to automate testing of their web applications. This is definitely a good thing. But it happens that they focus more on the tooling than the testing.
Read more →Sometimes you want to verify that an exception is thrown in your code.
Let me show you three different ways to verify that the expected exception has been thrown.
Read more →When should you use which assert? It is a question developers new to unit tests may ask themselves.
It is easy as a seasoned developer to think that this is obvious. It isn't when you are learning.
Read more →How do you create a zip file with Java? One option is to use Apache Commons Compress.
This example shows you how.
Read more →A template for creating web pages is great if you want to integrate front- and backend easy. I have been using Mustache for a while and I'm quite satisfied. It works great with both Dropwizard and Spark
The documentation says how to include a snippet from another template. But searching for it was not that easy.
Read more →It is very convenient to run the unit tests separated from other, slower, tests. There are different ways to do this. One way is to have a separate module for the acceptance tests.
Separating the modules is acceptable in some cases. It is not acceptable in others. There is a simple way to separate the source code for the acceptance tests while keeping the it in the same project if you use Gradle. Separate the tests with different source sets.
Separation on source sets means that you will keep all the acceptance tests in another directory structure than the unit tests. If you use the usual separation of production code and test code, then all you want to do is to add a new source set that contains the acceptance tests.
Read more →I had a need to stub a method the other day that had a var arg method. I failed in stubbing it using Mockito. It disturb me a lot. But after mulling on the problem a while, I searched and found a simple solution.
Mockito has a anyVararg() method that you should use when you try to stub a method that takes a var arg
as argument.
Gradle is a build automation system. You write your build script in Groovy. This is different compared to other build system such as Ant or Maven. They both use xml. Using Groovy instead of xml gives you a lot of benefits. You have an entire programming language at your disposal. This mean that you can easily customize the build behaviour.
If you, however, want to be able to do the same thing in many projects, it may be a good idea to write a plugin that you can refer to from other projects. I will show you, step by step, how to implement a Hello World Gradle plugin.
Read more →This blog post is the same as the example I presented at GeeCON TDD in Poznan, Poland, January 2015. It is a step-by-step example that I hope you will be able to follow and implement yourself.
But before I begin with the implementation, let me reason about why you should care about BDD.
Behaviour Driven Development, BDD, is a way to try to bridge the gap between developers, who can read code, and people who are less fluent in reading code. Cucumber is not a tool only for acceptance testing. It is a communication tool where you can express examples in plain text that anyone can read. These examples can also be executed. They are the outcome from discussions between stakeholders, developers and testers.
Given this, the technical part of BDD that I will show you is the less important part. The most important part is the conversations that occurs and defines the application that should be implemented.
Read more →This is the example I implemented at JDD 2014 in Krakow, Poland at my Cucumber-JVM tutorial.
It is a (baby) step by step tutorial. The purpose for me taking baby steps is that you should be able to follow and implement the same things. Be prepared to spend some time with the implementation, it will probably take you a few hours.
Before we dive into the example, let me define what I am aiming for. My goal is to show you how an example (or specification if you want) can be executed. The example is written in plain text and is used to automate the testing of the system I will create. These executable examples can later be relied upon for regression testing and a living documentation.
Read more →Working with slow modules in Maven is a problem. People will not build the module as often as they need and they will therefore not find problems as early as they could.
A solution could be to separate some of the slow stuff to a separate module. One separation can be to have a specific module for slow tests. This will, however, not solve the problem, that the module is too slow.
A solution to the problem could be to only include it in the execution when you invoke a specific Maven profile. This would separate the execution of a slow module from the execution of the rest, fast, modules.
Let me implement a simple example with two modules. There is the first module, the application, that we always want to build. It has fast unit tests and it is therefore not hindering to execute it often. Then there is the second module, the acceptance tests. It requires you to fire up your application before it can be executed. It is therefore dead slow. As a developer you will probably only want to execute the acceptance test module now and then.
Let me show you one way to achieve this.
Read more →Suppose that you need to do something from a Java program on a remote Linux server? How can you do that?
One thing we know is that Linux servers usually supports ssh and that you can do everything you need from a command line. In other words, you need a Java implementation of ssh so you can execute whatever you need on the remote host. Next problem is to either implement ssh yourself or find an implementation that you can use. If you decide not to implement ssh yourself, you will probably prefer a self contained implementation so you don't have to include more dependencies than necessary. This is a good use case for Ganymed SSH-2 for Java. The only thing left is to:
I will show you one solution to 1 and 2 above.
Read more →How can you pass a parameter to a unit test parametrised with JUnitParams? The answer is simple: As any other parameter.
Read more →I watched a presentation by Zsolt Fabok a while ago and saw a technique I hadn't thought of before. How do you verify that a parameter is used in a simple way? Feed the method with something that usually doesn't work and verify that something happens.
Read more →Measuring the test coverage is something many people think is a good idea. But is it a good idea? It depends on the quality of the tests. Test coverage may be a good measurement if the tests are good. But suppose that we have a high degree of test coverage and bad tests?
I will show two examples of how to get a 100% test coverage using Cobertura. They will be based on a set of good tests and a set of bad tests.
Test coverage is calculated by recording which lines of code that has been executed. If the code has been executed through a test in a testing framework then we have calculated the test coverage.
The calculation is done using these steps:
We will be able to say that 47% of the lines in the source code has been executed. If the execution is done through test code, this will give us a measurement of the test coverage.
Read more →Getting started with Selenium WebDriver may be an issue. You must write some code and get the code running. I have created what I think is the smallest possible solution that could work. It consists of two files, a project definition and the actual test.
You will need to have Java and Maven installed. I will not tell you how this should be done, it depends on your environment and operating system.
Read more →What is JBoss Drools? It is a framework where you can create rules that defines when a specific action should be done. This could be done in code using conditions. Creating them using a rule engine can make it easier to combine many business rules with many actions.
I tried to get a JBoss Drools example up and running. It turned out that the examples I found on the web were either were very complicated, tried to solve all possible problems or was just incomplete. I ended up writing my own example where I have removed everything that I didn't find necessary.
I divided this example in two parts. First part is the simplest possible solution that could work, a Hello World. In the second part I try to do something that actually could be useful. I trigger a rule and instantiates a class that could perform some action.
Read more →An example is perhaps the best way to describe something. Concrete examples are easier to understand than abstract descriptions.
I will show how Cucumber-JVM can be used to specify an example and how the example can be connected to the system under test, SUT. The example can then be executed using any IDE or using Maven.
Read more →The way Maven file structure is defined is a great way to separate unit tests and production code. Unit tests are fast. So fast that developers developing using Test Driven Development, TDD, doesn't have any performance problems when applying the Red-Green-Refactor cycle in their work. A large unit test suit is expected to be executed in seconds.
There is, however, no standard on how the files should be structured for slower tests (integration/acceptance/system et.al.). A common property for these tests is that they are slow. They often require a complete system setup in a known state. They use the filesystem, network, database and similar slow resources. Slow tests are normally not executed often. Developers seldom have the patience to wait for a build a long time before writing the next thing. Using them in a Red-Green-Refactor cycle is not practical. It takes too long time.
So what options do we have to separate the fast units tests and the slow tests? There are two main tracks that I have explored.
JUnit supports annotations so a method can be executed first in a test class or before each test method is executed. It also has annotations that supports methods to be executed after each test method or after the test class. This is very good if you need a common setup and a common tear down.
The after methods don't give you access to the test result. You cannot know if a test method failed or not. This may
pose a problem if you have a need to perform some specific actions after a failed test. A solution could be to
implement an onError() method. But JUnit doesn't support it.
A solution is to employ a @Rule annotation.
Read more →A test template for JUnit tests doesn't exist out of the box for IntelliJ IDEA. Creating one is not complicated.
The goal is to create a simple template that will assist you when you need to write a test in JUnit. I want it to look something like this:
Read more →Enabling second level cache in a JBoss when you use JPA 1 is actually relative easy. Understanding how to set its properties is also not to difficult to do. Finding how to specify which configuration file to use when setting the additional configurations is more difficult.
Read more →It works on my machine!
Ever heard that from a developer? I have, and it happens that the reason is that it actually works on their machine. It may also be the case that the order in which tests are executed matters. Test classes depends on each other and the order they are executed in is important. The solution is to execute the tests in random order so that any dependencies between tests are found and can be removed.
Read more →A colleague asked that question the other day. What is a good test? It is a really difficult question to answer. There are a number of properties that hold true for a good test. I will list some of them and discuss why I think they are important. Others may think that the order of importance is different or that other properties are more important then those that I list.
I will show some examples using Java and JUnit of what I think are bad tests and how they can be refactored to something better.
Tests are automated in my world. I always try to avoid manually testing. The main reason for this is that manual testing is slow and hard to repeat arbitrary many times. Therefore, test should be read as automated test in for the rest of this text.
Read more →Test driving a project should result in a test coverage of 100% of the code. But how can we know what test coverage we have? Is it even important?
Read more →Train accidents are mostly considered to be bad things. People tend to get hurt when trains have accidents. Never the less, it is not so uncommon with train wrecks in software development.
Train wreck code is code that calls a method on the return value of another method call. This chain can be very long if a value is excavated deep down in a object graph.
Read more →The simplest possible solution that could work. Ever heard that expression? What does it mean? Really?
The answer is obviously something that in a really simple way satisfies the test you currently are working on. Nothing more, nothing less.
Read more →I just had test in a Maven build fail with
java.lang.OutOfMemoryError: Java heap spaceRead more →
Have you ever wondered why your Maven project doesn't find and execute your tests?
Read more →An example is perhaps the best way to describe something. Concrete examples are easier to understand then abstract descriptions.
I will show how Cucumber-JVM can be used to specify an example and how the example can be connected to the system under test, SUT. The example can then be executed using any IDE or using Maven.
Read more →Development guided by test is perhaps the best way to make sure that your solution works and is possible to verify. I will show how you can develop a database layer guided by tests. It will be divided into two parts. The first part will be an in memory solution and the second part will be implemented using Java Persistence API, JPA, and Hypersonic. The second implementation is supposed to replace the first one guided by the tests developed for the in memory solution.
Read more →During a coaching session I got a question about a loop.
Would there be any difference in the output from a loop defined as
for (int i = 0; i < 3; i++) {
System.out.print(i + " ");
}
and a loop defined as
for (int i = 0; i < 3; ++i) {
System.out.print(i + " ");
}
in Java?
Read more →
Generics has been a a part of Java since Java 5. It will allow you to write code that handles types without deciding
which type upfront. This is of course very useful for collections. It used to be done using the inheritance system
and casting Object to the type you knew should be used.
Hamcrest is a great framework for assertThat and it is bundled with JUnit. It is getting some competition from another framework, the FEST assertThat framework. The idea behind FEST is to use a fluent interface. This means that you can use your development environments code completion features to build your asserts. Its main goal is to improve test code readability and make maintenance of tests easier.
Read more →Creating an executable jar from Maven is not really hard.
This example will show you how you can include stuff in a jar and make it executable while not including stuff that is needed only during the build.
Read more →Chasing the warning:
[WARNING] Using platform encoding (MacRoman actually) to copy filtered resources, i.e. build is platform dependent!Read more →
We had a problem in my current Java project. Whenever somebody wrote a comment using Swedish national characters, åäö or ÅÄÖ, and later tried to build the system with Maven we got the error:
unmappable character for encoding UTF-8Read more →
We want to perform an integration test of a system using Maven. The application must be deployed on an application server and the application server must be started before we can perform the integration tests. The application should be undeployed and the application server should be terminated after the integration test has been performed no matter what the result of the test was.
How can this be achieved with Maven?
Read more →We want to run the same test more than once and only vary the parameters. The solution is to use JUnit and run our tests with the Parameterized JUnit runner.
Read more →I want to build a Hello World example for JBoss ESB using Maven instead of Ant. The original example bundled with JBoss ESB is using Ant. I have created a pom.xml that will do all the magic and re-located the example files to fit into a Maven structure.
Read more →Dependency injection is invaluable when building software. Decoupling components means that it is possible to test them independently.
Read more →We want to convert a POJO, Plain Old Java Object, to xml and we don’t want to alter the POJO in any significant way. How can this be done?
Read more →Open source is a great thing when it works. It happens that the documentation is less then perfect or that the examples provided doesn't work out of the box.
Read more →A quick Continuous Integration introduction example.
Read more →We want to build a web application and we want to test it automatically.
Read more →We will create a small Java application that connects to a database using Hibernate. We will use Spring to wire stuff together and Maven to build it.
Read more →I want to to create a very simple web application using Spring. I want to create it using Maven as build tool.
Read more →