Recently I was debugging my code and I could not see why my test was failing. It took me about 20 minutes to see that I violated one rule I try to follow. One assert per test.
After tweeting it I got some reaction ranging from ‘this is a very silly guideline’ to ‘Tests should test one thing. Often one assertion, but not always.’. I, of course, tend to agree the latter one.
So what’s in for you when you use one assert per test? What are the problems?
One the plus side:
The other side:
I try to do one assert per test. Once in a while my code reviewer catches one of the multiple asserts per test. Some times this is ok, some times I fix it.
My rule is to have one assert per test almost every time. But try it at least.
And while on it, use a better assert lib. Both JUnit and TestNG Assert confuse the heck out of me. Ansgar introduced FEST Fluent Assertions Module to our team. Now my tests look something like:
@Test
public void testAddSubscriber() {
TestEventSubscriber eventSubscriber = new TestEventSubscriber();
eventPublisher.registerSubscriber(eventSubscriber);
assertThat(eventPublisher.getEventSubscribers()).
containsOnly(eventSubscriber);
}
If you don’t know it, try it. I do like it.
Which thoughts do you have ?
I use Apache Trinidad at work and since JSF 2 is now final I decided to play with it a bit.
Of course this is going to be the classic Hello World example (as there are many other like this around the web).
First you need to setup a simple Maven project.
The file layout should be something like that.

Directory Layout for JSF 2 Ajax Demo
After that change your pom.xml to include the servlet and jsf2 libs.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.maxheapsize</groupId>
<artifactId>jsf2demo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>jsf2demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.0.0-b13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.0.0-b13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<finalName>jsf2demo</finalName>
</build>
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2</url>
</repository>
</repositories>
</project>
First we are going to create the managed bean to hold the name we are going to enter.
package com.maxheapsize.jsf2demo;
import javax.faces.bean.*;
import java.io.Serializable;
@ManagedBean
@SessionScoped
public class HelloWorldBean implements Serializable {
private String name = "";
@ManagedProperty(value = "#{demoService}")
private Service service;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setService(Service service) {
this.service = service;
}
public String getReverseName() {
return service.reverse(name);
}
}
To demonstrate the dependency injection with JSF 2 I use a service to reverse the name. Simply add the @ManagedProperty with the name of the service and it will get injected. Of course we need the service. Here it is:
package com.maxheapsize.jsf2demo;
import javax.faces.bean.*;
@ManagedBean(name="demoService")
@ApplicationScoped
public class Service {
public String reverse(String name) {
return new StringBuffer(name).reverse().toString().toLowerCase();
}
}
Very simple…isn’t it ?
The only thing what’s missing is the web.xml and the webpage itself.
The web.xml is pretty straight forward and should not show any surprises.
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Web Application</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
</web-app>
The index.xhtml has some differences from earlier versions of JSF. First, JSF now supports Ajax out of the box. To have this enabled you need to load the jsf.js javascript library. The inputText tag binds to our managed bean and includes an f:ajax tag. This tag determines which part should be rerendered (in this case the element with the id reverseName). F:ajax will execute on value holding components always with an ‘onchange’ event and on action components (like commandButtons) with an ‘onclick’ event.
The output will trigger the injected service in our managed bean and return the reversed input string.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>JSF Demo</title>
</h:head>
<h:body>
<h:outputScript name="jsf.js" library="javax.faces" target="body">
</h:outputScript>
<h1>Ajax JSF 2 Demo</h1>
<h:form>
<h:inputText id="name" value="#{helloWorldBean.name}">
<f:ajax render="reverseName"/>
</h:inputText>
<h:commandButton value="Say reverse Hi via Ajax">
<f:ajax execute="name" render="reverseName"/>
</h:commandButton>
<h:outputText id="reverseName" value="#{helloWorldBean.reverseName}"/>
</h:form>
</h:body>
</html>

JSF 2 Ajax Demo
And that’s it. Sure it’s a simple example, but so far I do like the minimal configuration and the ajax integration.
Here is a small update on my little fun project.
I released version 0.2 of quant. Now it will recognize all TestNG annotations which do not have a TestNG group (like @BeforeMethod, @BeforeClass etc.). The method ‘reportViolation’ on ClassTester will now report whats wrong with the examined class.
[/java]
assertFalse(classTester.isInvalidTestClass(),
classTester.reportViolation());
[java]
Above code will now report:
java.lang.AssertionError: Report for Class com.maxheapsize.quant.testclasses.SetupMethodWithoutTestGroup Ignore abstract classes: true Specified TestGroups : + testUnitTest * Methods with wrong test group: - testSetUp
In this way you know what went wrong and where to look for it.
Quant is now also available in my repository. To include it add the following code to your pom.xml.
<dependency>
<groupId>com.maxheapsize</groupId>
<artifactId>quant</artifactId>
<version>0.2</version>
</dependency>
For now you need to add my mvn repository to your pom. I’m about to have it mirrored to the official servers.
Have fun.
Did you ever wondered if all tests your team wrote are really running ? How many disabled tests does your code base have? How many public void methods do not have a @Test annotation (or at the class) ?
I saw all of that in the last years.
To overcome this situation I wrote a couple of java classes which will scan your java test sources and will examine the annotations (for TestNG, sorry JUnit). The code will detect if all public void methods do have a @Test annotation (either direct on the method or on the class) or if there are disabled tests. Both signals are most likely a sign of rotten code.
If you have different test groups defined like ‘unitTest’ or ‘integrationTest’ you want to make sure all tests are in at least one test group. This ensures if you run all test groups all tests are executed.
The usage is really simple. To make sure all your tests are ok is to write just another test which will check all tests.
ClassFinder classFinder =
new ClassFinder.Builder(sourceDirectory).build();
for (Class klass : classFinder.getClassList()) {
TestClassTester testClassTester =
new TestNGTestClassTester.Builder(klass).build();
Assert.assertTrue(testClassTester.allTestMethodsHaveValidTestGroup());
}
You need to specify the source files of your code so that all java files can be scanned. It is possible to exclude certain packages to be checked (via TestNGTestClassTester.Builder(klass).addExcludedPackage("testclasses").build()). After gathering all class names from the sources the code will check for @Test annotations in the test classes. You can also specify the test groups which all test should belong to (via addTestGroup("unitTest") in the builder).
Finding disabled test methods is very simple too (one of the unit tests)
@Test
public void testNoDisabledTest() {
DisabledTestFinder unitUnderTest =
new TestNGDisabledTestFinder.Builder(TwoTestGroups.class).build();
assertFalse(unitUnderTest.hasDisabledTests());
}
This would test a single class (but you can of course feed it with the results of the ClassFinder).
If you combine the possibility to break your build because of defect test classes and a continuous integration system, you can make sure everybody will annotate their classes correctly or never disables tests (or even better use a CI with delayed check in and personal build like Jetbrains Teamcity). Of course you can define your own thresholds for e.g. 30 disabled tests are allowed (I know sometimes you just can’t avoid it).
The code depends on testng and commons-io and is released under the Apache v2 license.
I still need to figure out where to put the maven2 sources. Either Google code or GitHub ? Any ideas?
Update: Code is available at Google Code Hosting.
Things to implement:
Jetbrains released a Google App Engine plugin for their IntelliJ IDE. I did not see any announcement about this at all.

New project inside IntelliJ for Google App Engine
You will have a new option when creating a new project. After supplying the path to the local app engine SDK your almost good to go. I needed to add the app engine jars as libraries to my project. That being out of the way you can start coding, run you local server (a pre configured run configuration is supplied) and also deploy it to Google all from within IntelliJ. I tested it with a very basic example with local development and remote deployment and this works really nice.
Thanks Jetbrains.
From the release notes:
This plugin provides the following features:
I’m pretty busy at work right now but I could find some time to add one more feature to my little property sorter plugin for IntelliJ Idea.
Comments above property entries will now be preserved when you sort the file.
The plugin is available from within Idea or at Google Code.

From unsorted ...

... to sorted with comments.
At Campfire One Google announced their App Engine for Java (this was in the rumor mill for a couple of days already). The first 10,000 developers would get an early look at App Engine’s Java language support. I would have almost missed it. Some tweets reminded me of registering with Google. I heard of AppEngine before but the fact that it was only available for Python did not make it very attractive to me. Now the game changed a bit with introducing Java (and other JVM languages (JRuby, partial Scala …), well Groovy for sure, Ola Bini has more on that).
After registering with my Google ID they wanted to verify my account with a sms text message. Google is just listing 3 countries and then ‘Other’ for sms verification and I expected it would not work with a german cellphone. But it did
.
The Tutorials on their site are working nicely (even if you don’t have Eclipse which they are always referring to). Just follow the instructions step by step, use ant and the command line to get through the examples. Don’t copy the template project, this is not in line with the documentation.
In the last hour or so I went from nothing to a running Guestbook App at Google (try it!). Once you get the environment right, the code is pretty straight forward.
I see a couple of things which I do like about the App Engine.
Support for Google Id and Sign In
AppEngine support sign in with an Google ID with 2! lines of code. Great. I don’t want to worry about that (this generates the Google login page and redirects).
UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser();
Automagic Persistence
With simple annotation you persist your objects. No mapping, no nothing. You can configure if you want to be using JDO or JPA. No database hassle or whatsoever. Of course it needs to be seen how this work with more complex domain models.
@PersistenceCapable(identityType = IdentityType.APPLICATION)
..
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
@Persistent
private User author;
@Persistent
private String content;
@Persistent
private Date date;
...
Local Development – Remote Depolyment
Everything works locally. If you deploy it to Google it uses the Google facilities. I don’t have to worry (deployment is one ant command).
Scalability and free Use
If your application is successful you can grow with Google. More Resources at your fingertips. Of course this costs money (but you should make money at this point right?). If you are beyond the free 10 GB bandwidth in/day, 10 GB bandwidth out/day, 5 million pageviews a month, 46.3 cpu h/day and 1000 emails/day you pay:
Monitoring
You get nice and detailed overview of the status of you application. You can upload new version any time and go live on demand.

Google AppEngine Dashboard
This this is limited access and Google titles it ‘early look’ there must be some gotchas but I hope they will get worked out. Of course you will depend on Google’s code but I could imagine with a good abstraction layer you can minimize the dependencies to the AppEngine (although replacing some services you might need to use could be hard).
The downside of using it are (gathered from various sources)
For sure there are some more benefits in hosting with Google (I guess the same goes for Amazon with S3/EC2). In the past I heard from a couple of startups using those kind of services but I never imagined that it would be that easy. As I said, I was up and running in under one hour.
I certainly will use AppEngine for a small application in the near future.
I do work with language property files pretty much every day (since I’m the GUI guy in the team). The files are updated on different branches copied up to the trunk and merged down to new branches, sometimes even updated by our product owner. We got a couple of times into not so funny merge conflicts since people did not sort the property files in the same way. To get around that we used an external tool to sort the files just before committing them.
Right, we can do better than this.
I wrote a small plugin for IntelliJ IDEA (and turns out my colleague too) for sorting these inside IDEA. I took the easy approach to sort them in the editor window. Simply open a properties file and choose Code – Sort Properties. It detects if this is a real properties file (e.g. all lines do have a # at the start or do follow the pattern key=value) and sorts them. If things go boom you always can undo
.
You can get it from here. It’s just 7KB since I did not include the testng jars.
Today I got an interesting ctrl+space code completion in IDEA 8.1. Easteregg anyone ?

Update: Seems like this is part of IDEA since at least release 4.0.
I do love IntelliJ IDEA but the 8.0 release had some issues with indexing and compiler caches.
Version 8.1 is out and addresses these issues (among other things, e.g. git support). Hurray.