Associating Xtext editors to file names, instead of file extensions
I’m currently working on a Xtext-based editor for Google’s BUILD language, as described in our Google Engineering Blog. BUILD files do not contain an extension, they are simply named “BUILD.” This naming convention made working with Xtext quite challenging. I needed to change Xtext’s default behavior: instead of associating Xtext editors to file extensions, I needed to associate them to file names. In this blog post I’m describing how I was able to accomplish this.
In this post I’ll be using a brand-new Xtext project. To keep things simple, I’ll use the default file extension (mydsl) and grammar. You can get the source code of this post from Xtext Samples, a new open source project where I plan to store the code I use in Xtext-related posts. All code is released under the Eclipse Public License (EPL) 1.0.
The following steps assume we are going to associate our Xtext editor with the file name “MyDsl.”
- Modify the plug-in’s
XtextEditorto make it understand file names, instead of file extensions. - Create a
ContentHandlerthat describes the content of files with name “MyDsl.” As part of this step we need to create a new content type for “MyDsl” files. - Create an
IResourceServiceProviderthat provides services (e.g. validation, content description, encoding) to files with name “MyDsl.” - Register the classes created in the previous steps, to make them visible to EMF and Xtext.
1. Modify the plug-in’s XtextEditor to make it understand file names
This is the easiest of all steps:
- Open the file plugin.xml in the “ui” project.
- Select the “plugin.xml” tab at the bottom of the editor, to edit the XML code directly.
- In the
editorelement, replaceextensions="mydsl"withfilenames="MyDsl"
2. Create a ContentHandler that describes the content of files with name “MyDsl”
Here is a simplified version of our ContentHandler. You can find the complete file here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class MyDslContentHandler extends ContentHandlerImpl { public static final String MY_DSL_FILE_CONTENT_TYPE = "com.google.eclipse.MyDsl"; @Override public boolean canHandle(URI uri) { return isMyDslFile(uri); } @Override public Map<String, Object> contentDescription(URI uri, InputStream inputStream, Map<?, ?> options, Map context) throws IOException { Map<String, Object> description = super.contentDescription(uri, inputStream, options, context); if (canHandle(uri)) { description.put(VALIDITY_PROPERTY, VALID); description.put(CONTENT_TYPE_PROPERTY, MY_DSL_FILE_CONTENT_TYPE); } return description; } } |
Line 2: We define a new content type for “MyDsl” files. We keep the constant public since we will be using it later.
Line 4: We specify that file names with name “MyDsl” can be handled by the ContentHandler. We call the utility method isMyDslFile(URI) from the class URIs.
Line 8: We declare the content of “MyDsl” files as valid and associate its type to the one defined in line 2.
3. Create an IResourceServiceProvider that provides services to files with name “MyDsl”
Here is a simplified version of our IResourceServiceProvider. You can find the complete file here.
public class MyDslResourceServiceProvider extends DefaultResourceServiceProvider { @Override public boolean canHandle(URI uri) { return isMyDslFile(uri); } }
We call the utility method isMyDslFile(URI) from the class URIs to specify that this IResourceServiceProvider can handle files with names “MyDsl.”
4. Register the classes created in the previous steps, to make them visible to EMF and Xtext
Now it’s time to wire up everything together. First, we bind IResourceServiceProvider to our MyDslResourceServiceProvider in the plug-in runtime module:
public Class<? extends IResourceServiceProvider> bindIResourceServiceProvider() { return MyDslResourceServiceProvider.class; }
Now we tell Xtext and EMF, in MyDslUiModule‘s constructor, to understand files named “MyDsl.”
public class MyDslUiModule extends AbstractMyDslUiModule { public MyDslUiModule(AbstractUIPlugin plugin) { super(plugin); configureXtextToWorkWithFileNames(new InjectorProvider()); } }
We pass an InjectorProvider that obtains the plugin’s Injector only at the moment when it is needed. At this point we cannot pass the Injector directly, since it has not been fully constructed when configureXtextToWorkWithFileNames is called.
The method configureXtextToWorkWithFileNames(InjectorProvider) is defined in XtextSetup:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | final class XtextSetup { static void configureXtextToWorkWithFileNames(InjectorProvider injectorProvider) { register(new MyDslContentHandler()); register(new ResourceFactoryDescriptor(injectorProvider)); register(new ResourceServiceProvider(injectorProvider)); } private static void register(ContentHandler h) { ContentHandler.Registry registry = ContentHandler.Registry.INSTANCE; registry.put(HIGH_PRIORITY, h); } private static void register(Resource.Factory.Descriptor d) { Resource.Factory.Registry registry = Resource.Factory.Registry.INSTANCE; registry.getContentTypeToFactoryMap().put(MY_DSL_FILE_CONTENT_TYPE, d); } private static void register(Provider<IResourceServiceProvider> p) { IResourceServiceProvider.Registry registry = IResourceServiceProvider.Registry.INSTANCE; registry.getContentTypeToFactoryMap().put(MY_DSL_FILE_CONTENT_TYPE, p); } } |
Line 4: We register the ContentHandler we created in step 2.
Line 5: We associate the IResourceFactory in the plug-in’s Guice module with the content type defined in step 2.
Line 6: We associate the IResourceServiceProvider we created in step 3 (and later on registered in the plug-in’s Guice module) with the content type defined in step 2.
Testing the editor
To run the editor, right-click any of the projects and select “Run As” > “Eclipse Application” from the context menu.
Here is a screenshot of the editor opening a file named “MyDsl”

Summary
In this post I have shown how to make Xtext understand file names in four easy steps. You can find the code for this post in the project Xtext Samples. You can checkout the code, browse it or download it.
Even though I spent a good amount of time reading Xtext and EMF code to figure this out, I cannot claim my solution is the best one. Please let me know if you know a better way to do what I described in this post :)
Feedback is always welcome.
Upgraded to Xtext 2.1: first impressions

During this past weekend I upgraded protobuf-dt to the new and shiny Xtext 2.1.1. I didn’t have a real need for the upgrade, the protocol buffer editor has been working well with version 2.0. It was mostly curiosity.
Once again, the Xtext team did a great job. We, Xtext users, got an early Xmas gift. Soon after upgrading I was pleasantly surprised by some pretty good improvements. These are my favorite ones:
- Removing grammar ambiguity is easier. The soon-to-be-released version 1.1 of the protocol buffer editor aims at supporting 100% of the language syntax and scoping rules. Unfortunately the grammar for the protocol buffer is ambiguous, and I was having a hard time cleaning it up (I’m still a Xtext newbie.) The syntactic predicates I added to remove ambiguity in the grammar did not work in 2.0, but they worked fine in 2.1!
- Speed, speed, speed. My tests now execute considerably faster. Now I can run them constantly (even the integration tests,) without losing context. Note: I don’t have any numbers to back up this claim (I wasn’t even expecting any speed improvements.) I was just amazed to see how fast my test suite now runs.
- Rename refactoring now works. In Xtext 2.0 I had a few use cases where rename refactoring did not work well. It is all fixed in Xtext 2.1.
- Marker customization. Xtext comes with a really nice framework for adding semantic checks to your editor. Unfortunately, in Xtext 2.0 all editor markers created by this framework were of type “Xtext Check.” There was no way to change such type (e.g. “Protocol Buffer Problem.”) Now this is fixed in 2.1 (tracked as bug 351963.)
Please note that these are just my first impressions after upgrading, I’m sure there are more goodies in Xtext 2.1 :)
As a side note, one of my sessions proposals, “Xtext Success Story at Google,” got accepted for EclipseCon 2012 as an early-bird pick. I hope to see you there!
A simple way to test Eclipse-based editors
After two releases of the open source version of protobuf-dt and ten Google-internal ones, code complexity grow to a point that more comprehensive testing is needed. Even though the practices in this post can be used to test different aspects of an Eclipse editor, we’ll focus on testing scoping.
Verifying that scoping works correctly involves:
- Specifying and parsing protocol buffer-content to use for testing
- Find a specific element in the parsed file
- Verify that scoping returns all the possible elements that can match the element found in step #2
An additional requirement is to make tests as lightweight as possible (e.g. do not require to instantiate a full Eclipse for running tests.)
1. Specifying and parsing protocol buffer-contents to use
My first attempt was to put all the protocol buffer code in a StringBuilder and then passed it to my XtextRule to get an AST back, as follows:
@Rule public XtextRule xtext = createWith(integrationTestSetup()); @Test public void should_provide_Property_fields_for_custom_field_option() { StringBuilder proto = new StringBuilder(); proto.append("package com.google.proto; ") .append("import 'google/protobuf/descriptor.proto'; ") .append(" ") .append("extend google.protobuf.FieldOptions { ") .append(" optional int32 code = 1000; ") .append(" optional int32 info = 1001; ") .append("} ") .append(" ") .append("message Person { ") .append(" optional boolean active = 1 [(code) = 68];") .append("} "); Protobuf root = xtext.parseText(proto); // test implementation }
Needless to say, writing and maintaining this is a real PITA. To make it readable I have to add extra whitespace to each line so the whole thing looks square. In addition, copy/paste code from the protocol buffer editor requires also adding append and quotes to each line, plus formatting. On top of that, it makes the test method too long.
An alternative approach was to have .proto files in the file system. I was not happy with this approach since anybody reading the code will need to go to two places to understand what the test is doing.
Finally, I found a better approach: specify the protocol buffer text as a comment!
I didn’t come up with this idea myself, I’m just borrowing it from CDT. After implementing a simpler, but similar approach, my test looks like this:
// package com.google.proto; // import 'google/protobuf/descriptor.proto'; // // extend google.protobuf.FieldOptions { // optional int32 code = 1000; // optional int32 info = 1001; // } // // message Person { // optional boolean active = 1 [(code) = 68]; // } @Test public void should_provide_Property_fields_for_custom_field_option() { Protobuf root = xtext.root(); // test implementation }
This is a big improvement! First of all, the test method ends up being shorter and easier to read. Second, it is easy to type something in the protocol buffer editor, copy it, and paste it above a test method. Then I just have to highlight it and press Ctrl+/ to have the text converted to a comment.
In this new scenario, my custom XtextRule does the following,:
- extracts the comment of each test method and creates a method name > comment mapping
- parses the comment of a test method and creates an AST just before executing the test method, not earlier
- keeps a reference to the root node of the AST, to be used by the test method itself
It looks good, but what about imported .proto files?
When testing scoping, it is absolutely necessary to verify that imported types are included correctly.
I originally had .proto files to be imported in the file system and stored in Git, which is ugly for the reason I mentioned before.
To make things better, I borrowed another idea from CDT: specify the text and file name of the .proto file to be imported in comments, XtextRule will create the file in the file system just before executing a test method.
Here is an example:
// // Create file custom-options.proto // // package com.google.proto; // // import "google/protobuf/descriptor.proto"; // // extend google.protobuf.FileOptions { // optional int32 code = 1000; // optional int32 info = 1002; // } // package com.google.proto; // // import 'custom-options.proto'; // // option (code) = 68; @Test public void should_provide_imported_Property_fields_for_custom_option() { // test implementation }
In the example above we have two comments for a test method. The first one tells my XtextRule to create a file named “custom-options.proto” before executing the test method. The second comment will be the one parsed and whose AST will be stored by the XtextRule (just like in the previous example.)
Neat, isn’t it? :)
2. Find a specific element in the parsed file
This step is necessary to ensure that scoping returns all the possible types that a given reference may be pointing to.
In this example:
// package com.google.proto; // import 'google/protobuf/descriptor.proto'; // // extend google.protobuf.FieldOptions { // optional int32 code = 1000; // optional int32 info = 1001; // } // // message Person { // optional boolean active = 1 [(info) = 68]; // } @Test public void should_provide_Property_fields_for_custom_field_option() { }
my test is going to verify that scoping returns the field options code and info as potential matches for (code). To do so, I first need to find the proper AST element that (code) represents.
Let’s say I want to search for the custom field option info. My original approach would require the following:
- Find all the elements in the AST of type
CustomFieldOption - If any result is returned from #1, find the one whose name is “info”
Here is an example:
Protobuf root = xtext.root(); // statically imported from CustomFieldOptionFinder CustomFieldOption option = findCustomFieldOption(name("info"), in(root));
This solution by itself is not too bad, and it works! Unfortunately it requires one specialized finder per type in the AST. For a relatively simple language like Protocol Buffers, it would require more than 10 finders, which is too much code to maintain just for testing.
Enter CDT with a better approach, which requires only one finder for all the types in the AST. This finder looks for elements this way:
- Find the first element matching some text
- Verify that the found element is of the the specified type and has the specified name
For example:
CustomFieldOption option = xtext.find("info", ")", CustomFieldOption.class);
To find the custom option “info” this finder will:
- concatenates the
Strings passed as arguments and find the first element that matches the text “info)” - verify that the found element is a
CustomFieldOptionand has name “info” (the firstStringargument only)
As you can see, this approach is the complete opposite of my original one.
Since only one finder is needed, I can have my XtextRule create it and pass the root of the AST to it. This way, I don’t have to pass it to the finder every time I perform a lookup.
3. Verifying that scoping returns the correct types
This is actually DSL-specific. My only recommendation here is, if you are using JUnit, write your own Hamcrest matchers to keep test code short and readable, and without duplication.
Putting it all together
Here is how one of my tests for protobuf-dt looks like:
// message Person { // optional Type type = 1 [ctype = STRING]; // } @Test public void should_provide_Property_fields_for_native_field_option() { // We have an overloaded version of "find" that takes only one <code>String</code>, // to be used when the text to find and the name to match are the same. NativeFieldOption option = xtext.find("ctype", NativeFieldOption.class); IScope scope = provider.scope_PropertyRef_property(option.getProperty(), reference); Collection<Property> fieldOptions = descriptor().optionsOfType(FIELD); assertThat(descriptionsIn(scope), containAll(fieldOptions)); }
Please feel free to click these links to find the code of:
XtextRuleModelFinder- or just get the project’s source code, as described here
Feedback is always welcome! :)
Future posts
There are a couple of useful things I have done with Xtext that I’d like to blog about in the near future:
- Adding spell checking to comments and strings
- Opening files outside an Eclipse workspace
- Making Xtext work with file names, instead of file extensions
Now it is a matter of finding the time and energy!
What I am doing at Google
It has been eight months since I joined Google. Honestly, I have never, ever been this happy in my entire career. Google is a great place, for many reasons. The free food and the perks are nice indeed, but it is not what makes Google such a special place.
What matters to me is that I’m enjoying what I’m doing. Did I say “enjoying”? I love what I’m doing. I work on development tools, all Eclipse-based. This is what I asked to work on when I joined. For me, development tools is one of the most interesting domains in Software Engineering. I could go on and on explaining why, but let’s just say that I feel I’m developing for myself: I am part of the target audience of the software I write. I spend most of the time in Eclipse, and I like to build stuff that makes my experience better.
I was lucky enough to land in the Engineering Tools organization. My team is just great: super nice, talented and humble folks. Our job is to make Eclipse able to handle Google’s massive code base and to build support for Google-specific tools and languages. The following are the projects I’m currently working on:
- CDT integration with static code analysis tools (which BTW it is the topic for my talk at EclipseCon Europe 2011)
- protobuf-dt, an editor for Protocol Buffers (released as an open source project in August)
- support for our build language (described in our official blog)
- help organize “EclipseDay at Googleplex” with Ian Skerrett
I’ve also been visiting other Google offices (Zurich, New York, Seattle and Kirkland) co-presenting a tech talk. We gave this presentation the first time at Google’s headquarters. It was our Director that not only suggested us to take the tech talk outside of Mountain View, he actually encouraged us to do so. Needless to say, it was an awesome, mind-opener experience.
I will never forget how protobuf-dt became one of my main projects. It started as a toy I worked on for a few nights, on my own spare time (it was not even a 20% project.) I was so excited about the progress I made in such short period of time that I showed it to my Director during a 1:1.
His response was the following:
“Alex, this is great but I don’t want you to work on this at home anymore. When you are home, you enjoy your time with you family. From now on you work on this here, at the office.”
At the end of the conversation he added:
“I want you to work on what you like. I want you to be happy. When you are happy, you will be successful. Just let me know if there is anything I can do to help.”
I was completely shocked. I have never heard anything like that before. From that point on, I knew I was at the right place.
Probably you heard many stories about why working at Google is great. I just wanted to share mine :)
Not All Singletons are Evil

Among all the object-oriented design patterns, I think Singleton has the worst reputation. They have been called “evil,” “liars” and even “stupid,” and for good reasons:
- singletons are global access points, making client APIs hide their dependencies on them
- singletons make testing harder, mainly because they are hard to mock and inject
This is true, but only when Singletons are implemented and used in the “traditional” way:
-
Singletons cannot be extended (note that the class is
finaland the constructor isprivate)public final class MySingleton { private static final MySingleton INSTANCE = new MySingleton(); public static MySingleton instance() { return INSTANCE; } private MySingleton() {} public void doSomething() { // something here } }
-
Singletons are called anywhere in your code
public void someMethod() { MySingleton.instance().doSomething(); // keep doing stuff }
- Do not make the Singleton final, making creation of mocks from a Singleton possible (BTW, Mockito can mock non-final classes with private constructors.)
- Have the Singleton’s constructor package-protected. This is handy if your Singleton depends on other classes that need to be mocked during testing of the Singleton. This way, in your test, you can change the state of a new instance of the Singleton, without changing static state (that is, the state of the Singleton instance of a class.)
- Inject Singletons just like any other dependency, completely avoiding the “global access point” problem.
- extensible
- injected, and
- do not have static mutable state (state by itself is not bad)
Nothing is completely evil
Just like everything else, nothing is completely good or bad. I’ve been using Singletons in the next version of FEST-Assert in a way that avoids the problems mentioned earlier:
Sounds good. Show me the code!
The following code is similar to what we have done in FEST, but a lot shorter and simpler. You can also take a look at the code in the github repository.
Here is the Singleton:
public class MySingleton { private static final MySingleton INSTANCE = new MySingleton(); public static MySingleton instance() { return INSTANCE; } @VisibleForTesting MySingleton() {} public void doSomething() { // something here } }
Currently, I’m doing manual dependency injection, because I consider the project to be pretty small and I’m trying to keep external dependencies to a minimum. Of course, you can (and probably should) use Google Guice :)
public class SomeClient { @VisibleForTesting final MySingleton mySingleton; public SomeClient() { this(MySingleton.instance()); } @VisibleForTesting SomeClient(MySingleton mySingleton) { this.mySingleton = mySingleton; } }
As you may guessed by now, the constructor SomeClient(MySingleton) is used in tests, passing a mock MySingleton (and of course I also test that the default constructor uses the Singleton instance.) Any non-test code just calls the default constructor SomeClient().
Conclusion
Despite the bad reputation that Singletons have, they can still be pretty useful. As long as Singletons are:
they are as good as any other tool.
FEST-Assert 1.4: Fluent Interface for Assertions
Posted by Alex Ruiz in Java, Open Source, Testing on February 28, 2011
We are proud to announce that FEST-Assert 1.4 is out!
FEST-Assert is an “assertThat” library that provides a fluent interface for writing assertions. Its main goal is to improve test code readability and make maintenance of tests easier.
Example:
int removed = employees.removeFired(); assertThat(removed).isZero(); List newEmployees = employees.hired(TODAY); assertThat(newEmployees).hasSize(6) .contains(frodo, sam); String[] newHires = employees.newHiresNames(); assertThat(newHires).containsOnly("Gandalf", "Arwen", "Gimli"); assertThat(yoda).isInstanceOf(Jedi.class) .isEqualTo(foundJedi) .isNotEqualTo(foundSith);
One of the biggest changes in this release is the implementation of Ansgar’s "Self Types." By using this brilliant technique we ended up with a smaller, cleaner code base that is easier to maintain.
Here are some numbers, comparing this release with the previous one:
| Release | Lines of code | Tests | Code coverage |
|---|---|---|---|
| 1.3 | 3,132 | 3,707 | 98.7% |
| 1.4 | 2,051 | 1,849 | 100% |
Please note that 1.4 has more features than 1.3 and yet the code base is 35% smaller!
Release notes
Bug
- [FEST-378] - Newly added
assertThat(Iterable<?> actual)eagerly callsiterator()and can throw anNPE - [FEST-402] -
onPropertyis unable to access properties fromObjectclass - [FEST-414] - Impossible to use Fest Assert 1.3 with Ivy
- [FEST-415] -
IteratorAssertshould delayIteratorcomsumption as much as possible - [FEST-416] -
NPEinMapAssertdue to FEST-329
Improvement
- [FEST-105] - Add
isEither, orisOneOf - [FEST-413] - Implement Ansgar's Self Types
- [FEST-423] - User-friendly date and calendar formatting
New Feature
- [FEST-111] - Add support for regular expression matching to
StringAssert - [FEST-381] - collection
onProperty()assert might give nicer exceptions - [FEST-400] - Add generic assertions
isIn/isNotIn
You can download the latest release here (file fest-assert-1.4.zip.) FEST-Assert requires Java SE 5.0 or later.
Here are some useful links:
Feedback is always appreciated :)
Leaving Oracle
New year, new adventure!
Today is my last day at Oracle.
I have been working at Oracle for four and half years. It has been a pretty good time! I had the opportunity to work with great engineers, and I’m lucky enough to have them as friends.
It was difficult to leave Oracle without witnessing the release of JavaFX 2.0. All I can tell you is, this release will be the best ever!
I would like to thank all my former coworkers for all the terrific experiences we have shared. I wish you the best luck!
Oh BTW, for those of you wondering where I’m going, I accepted a job at Google. Tomorrow will be my first day there. I don’t know what I will work on yet but I’m sure it will fun! :)
A Closer Look at JUnit Categories

JUnit 4.8 introduced Categories: a mechanism to label and group tests, giving developers the option to include or exclude groups (or categories.) This post presents a brief overview of JUnit categories and some unexpected behavior I have found while using them.
1. Quick Introduction
The following example shows how to use categories: (adapted from JUnit’s release notes)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public interface FastTests { /* category marker */ } public interface SlowTests { /* category marker */ } public class A { @Category(SlowTests.class) @Test public void a() {} } @Category(FastTests.class}) public class B { @Test public void b() {} } @RunWith(Categories.class) @IncludeCategory(SlowTests.class) @ExcludeCategory(FastTests.class) @SuiteClasses({ A.class, B.class }) public class SlowTestSuite {} |
Lines 1, 2: we define two categories, FastTests and SlowTests. JUnit categories can be defined as classes or interfaces. Since a category acts like a label or marker, my intuition tells me to use interfaces.
Line 5: we use the annotation @org.junit.experimental.categories.Category to label test classes and test methods with one or more categories.
Lines 6, 9: test methods and test classes can be marked as belonging to one or more categories of tests. Labeling a test class with a category automatically includes all its test methods in such category.
Lines 14 to 18: currently programmatic test suites (line 17) are the only way to specify which test categories (line 14) should be included (line 15) or excluded (line 16) when the suite is executed. I find this approach (especially the way test classes need to included in the suite) too verbose and not so flexible. Hopefully Ant, Maven and IDEs will provide support for categories (with a simpler configuration) in the very near future.
Note: I recently discovered ClasspathSuite, a project that simplifies the creation of programmatic JUnit test suites. For example, we can specify we want to include in a test suite all tests whose names end with “UnitTest.”
2. Category Subtyping
Categories also support subtyping. Let’s say we have the category IntegrationTests that extends SlowTests:
public interface IntegrationTests extends SlowTests {}
Any test class or test method labeled with the category IntegrationTests is also part of the category SlowTests. To be honest, I don’t know how handy category subtyping could be. I’ll need to experiment with it more to have an opinion.
3. Categories and Test Inheritance
3a. Method-level Categories
JUnit behaves as expected when test inheritance is combined with method-level categories. For example:
public class D { @Category(GuiTest.class) @Test public void d() {} }
public class E extends D { @Category(GuiTest.class) @Test public void e() {} }
@RunWith(Categories.class) @IncludeCategory(GuiTest.class) @SuiteClasses(E.class) public class TestSuite {}
As I expected, when running TestSuite, test methods d and e are executed (both methods belong to the GuiTest category and E inherits method d from superclass D.) Nice!
3b. Class-level Categories
On the other hand, unless I’m missing something, I think I found some strange behavior in JUnit in this scenario. Consider the following classes:
@Category(GuiTest.class) public class A { @Test public void a() {} }
public class B extends A { @Test public void b() {} }
@RunWith(Categories.class) @IncludeCategory(GuiTest.class) @SuiteClasses(B.class) public class TestSuite {}
As we can see, TestSuite should execute the tests in B that belong to the category GuiTest. I was expecting TestSuite to execute test method a, even though B is not marked as a GuiTest. Here is my reasoning:
- test method
abelongs to the categoryGuiTestbecause test classAis labeled with such category - test class
Bis anAand it inherits test methoda
Therefore, TestSuite should execute test method a. But it doesn’t! Here is a screenshot of the results I get (click to see full size.)
There are two ways to fix this issue, depending on what test methods we want to actually run:
- Label class
BwithGuiTest. In this case, both methods,aandb, will be executed. - Label method
awithGuiTest. In this case, only methodawill be executed.
(I’ll be posting a question regarding this issue in the JUnit mailing list shortly.)
4. Categories vs. TestNG Groups
(You saw this one coming, didn’t you?) Categories (or groups) have been part of TestNG for long time. Unlike JUnit’s, TestNG’s groups are defined as simple strings, not as classes or interfaces.
As a static typing lover, I was pretty happy with JUnit categories. By using an IDE, we could safely rename a category or look for usages of a category within a project. Even though my observation was correct, I was missing one important point: all this works great as long as your test suite is written in Java.
In the real world, I’d like to define a test suite in either Ant or Maven (or Gradle, or Rake.) In this scenario, having categories as Java types does not bring any benefit. In fact, I suspect it would be very verbose and error-prone to specify the fully-qualified name of a category in a build script. Renaming a category now would be limited to a text-based “search and replace.” Ant and Maven really need to provide a way to specify JUnit categories, clever enough to be fool-proof.
As you may expect, I prefer the simplicity and pragmatism of TestNG’s groups.
Update #1: my good friend (and creator of the TestNG framework,) Cédric, reminded me that we can use regular expressions to include or exclude groups in a test suite (details here.) This is really powerful!
5. My Usage of Categories
I’m not using JUnit categories in my test suites yet. I started to look into JUnit categories because I wasn’t completely happy with the way we recognized GUI tests in FEST. We recognize test methods or test classes as “GUI tests” if they have been annotated with the @GUITest (provided by FEST.) When a “GUI test” fails, FEST automatically takes a screenshot of the desktop and includes it in the JUnit or TestNG HTML report. The problem is, our @GUITest annotation is duplicating the functionality of JUnit categories.
To solve this issue, I created a JUnit extension that recognizes test methods or test classes as “GUI tests” if they belong to the GuiTest category. At this moment GuiTest is an interface provided by FEST, but I’m thinking about letting users specify their own GuiTest category as well.
I also refactored this functionality out of the Swing testing module, expecting to reuse it once I implement a JavaFX testing module :)
You can find the FEST code that deals with JUnit categories at github.
6. Conclusion
Having the ability to label and group tests via categories is really a great feature. I still have some reservations about the practicality of defining categories as Java types, the lack of support for this feature from Ant and Maven (not JUnit’s fault,) and the unexpected behavior I noticed when combining class-level categories and test inheritance.
On the brighter side, categories are still an experimental, non-final feature. I’m sure will see many improvements in future JUnit releases :)
Feedback is always welcome.
Update #2: The nice folks at DZone have posted this entry at Javalobby.
Unexpected behavior in JUnit’s ExpectedException

In a previous post, I described my preference of the relative new ExpectedException rule over the more traditional strategies for verifying expected exceptions: the good-old “try-fail-catch” pattern and the “expected” attribute in JUnit’s @Test annotation. I thought, and I still think, that this new tool provides the best features of its predecessors: code brevity and the ability to specify which line of code is the one we expect to throw an exception. The only point I missed: it is not foolproof.
In a previous conversation with my good friend and colleague Stuart, we agreed that we need to be careful enough to place the check for an expected exception just before the line of code that is supposed to throw such exception, in order to verify that the exception is thrown at the correct time. The following example is taken from FEST’s Assertions:
// Note: I'm using the ExpectedException rule I created myself in the previous post. @Rule public ExpectedException thrown = none(); private StringAssert assertions; @Before public void setUp() { assertions = new StringAssert("Leia"); } @Test public void should_fail_if_actual_is_not_equal_to_expected() { thrown.expectAssertionError("expected:<'Yoda'> but was:<'Leia'>"); assertions.isEqualTo("Yoda"); }
So far, so good. A couple of nights ago, I discovered by accident that any code placed after the line that throws the exception will never get executed if the expected exception is actually thrown. For example, in the following code listing, I was checking that the mocks were correctly called after the expected exception is thrown (BTW, I’m using Mockito.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @Rule public ExpectedException thrown = none(); private StringAssert assertions; private Failures failures; @Before public void setUp() { assertions = new StringAssert("Leia"); failures = spy(Failures.instance()); assertions.failures = failures; } @Test public void should_fail_if_actual_is_not_equal_to_expected() { thrown.expectAssertionError("expected:<'Yoda'> but was:<'Leia'>"); assertions.isEqualTo("Yoda"); verify(failures).fail(assertions.info, isNotEqual(assertions.actual, "Yoda")); } |
The problem here is that line 15 will never be executed if line 14 throws the expected exception! This test will always pass as long as the expected exception is thrown, even if I remove the calls to Failures from StringAssert.
The reason behind this behavior is actually quite simple. By looking at the source of ExpectedException, we can tell immediately that once the expected exception is caught, it is impossible to continue the execution of the test method:
@Override public void evaluate() throws Throwable { try { fNext.evaluate(); } catch (Throwable e) { if (fMatcher == null) throw e; Assert.assertThat(e, fMatcher); return; } if (fMatcher != null) throw new AssertionError("Expected test to throw " + StringDescription.toString(fMatcher)); }
I fixed this test by replacing the ExpectedException rule with the traditional “try-fail-catch” pattern:
@Test public void should_fail_if_actual_is_not_equal_to_expected() { try { assertions.isEqualTo("Yoda"); fail(); } catch (AssertionError e) { assertEquals("expected:<'Yoda'> but was:<'Leia'>", e.getMessage()); } verify(failures).fail(assertions.info, isNotEqual(assertions.actual, "Yoda")); }
Not surprisingly, it turns out that Stuart had a similar thought about the subject. After a brief chat, we came up with the following patterns for using ExpectedException effectively:
- the check for the expected exception must be immediately above the code that is expected to throw such exception
- the line of code that is expected to throw an exception should be the last line in the test method
Update: The nice folks at DZone have posted this entry at Javalobby.
FEST at JavaOne 2010
Posted by Alex Ruiz in Conference, Java, JavaFX, Open Source, Swing on October 5, 2010

This past JavaOne was fun for sure. Since there is not too much I can add that hasn’t been covered by the media, I’m just going to talk about the session that Yvonne and I presented.
The title of the session was “Rich GUI Testing Made Easy.” Here is the abstract:
Testing GUIs is essential to making applications safer and more robust. Even the simplest GUI can enclose some complexity. Any complexity needs to be tested: code without tests is a potential source of bugs. A well-tested application has a greater chance of success.
GUI development has been slow to include automated testing as a core practice, because writing tests for GUIs is hard. In this session, we’ll explore several practices that can simplify testing of Swing and JavaFX GUIs.
The session went pretty well. My original thought is that there wouldn’t be too many many people attending, since our session was scheduled in the morning after the big Oracle party. To make things worse, the room we got was so hard to find. At the end, the room was full! and we got pretty good feedback about the presentation :)
You can find our slides here.
Many thanks to Peter Pilgrim for the picture!

My name is Alex Ruiz. I'm a programmer with special interest in Java, API design, Eclipse, testing and OOP. I'm the creator of 

