Groovy: Creating an Interface Stub and Intercepting All Calls to It

It's sometimes useful for unit testing to be able to create a simple no-op stub of an interface the class under test depends upon and to intercept all calls to the stub, for example to remember all the calls and parameters so that you can later verify that they've been invoked as expected. Often you'd use something like Mockito and its verify method but if you're writing unit tests in Groovy as I recommend then there is a simpler and in a way a more powerful alternative.
Continue reading →

Most interesting links of October

Recommended Readings


Continue reading →

JSF: Beware the Difference Between Build-Time and Render-Time Tags in Facelets

This is to remind me that I should never ever forget the cruical difference between build-time-only tags (i.e. having tag handlers only) and render-time tags that have corresponding components. The problem is that their lifespan is different and thus mixing them can easily lead to nasty surprises. Build time tags are used to modify the building of a component tree and have no effect during its rendering, where only the components participate.

A typical mistake is the nesting of ui:include (build-time) inside ui:repeat (render-time) using the var that ui:repeat declares:
Continue reading →

Never Mix Public and Private Unit Tests! (Decoupling Tests from Implementation Details)

It seems to me that developers often do not really distinguish between the various types of unit tests they should be writing and thus mix things that should not be mixed, leading to difficult to maintain and hard to evolve test code. The dimension of unit test categorization I feel especially important here is the level of coupling to the unit under test and its internals. We should be constantly aware of what kind of test we are writing, what we are trying to achieve with the test, and thus which means are justifiable or, on the contrary, not suitable for that kind of test. In other words, we should always know whether we're writing a Public Test or a Private Test and never ever mix the two. Why not and what actually are these two kinds of tests? Read on! (And if you agree or disagree, don't hesitate to share your opinion.)
Continue reading →

Hacking A Maven Dependency with Javassist to Fix It

Have you ever wondered what to do when needing "just a small change" to a third-part library your project depended on? This post describes how to use Maven and Javassist to take a dependency of your project, instrument it to modify its behavior, re-pack it, and release it as an artifact with a different name (so that you me depend on my-customized-lib instead of on lib).

The process is as follows:
  1. Phase process-sources - maven-dependency-plugin unpacks the dependency to classes/
  2. Phase compile (implicit) - compile the bytecode manipulation code
  3. Phase process-classes - exec-maven-plugin executes the compiled Javassist instrumenter to modify the unpacked classes
  4. Phase test - run tests on the instrumented code
  5. Phase package - let maven-jar re-package the instrumented classes, excluding the instrumenter itself

Continue reading →

Only a Masochist Would Write Unit Tests in Java. Be Smarter, Use Groovy (or Scala...).



I like writing unit tests but Java doesn't make it particularly easy. Especially if you need to create objects and object trees, transform objects for checking them etc. I miss a lot a conscise, powerful syntax, literals for regular expressions and collections, conscise, clojure-based methods for filtering and transforming collections, asserts providing more visibility into why they failed. But hey, who said I have to write tests in the same language as the production code?! I can use Groovy - with its syntax being ~ 100% Java + like thousand % more, optional usage of static/dynamic typing, closures, hundreds of utility methods added to the standard JDK classes and so on. Groovy support for example in IntelliJ IDEA (autocompletion, refactoring ...) is very good so by using it you loose nothing and gain incredibly much. So I've decided that from now on I'll only use Groovy for unit tests. And so far my experience with it was overwhelmingly positive (though few things are little more complicated by the positives more than compensate for them). Read on to find out why you should try it too.

(The arguments here focus on Groovy but I guess similar things could be said about JRuby, Scala etc. - with the exception of Java code compatibility, which you only get in Groovy.)

Few examples

Some of the example below use some Groovy magic but don't be scared. You can write Groovy just as if it was Java and only learn and introduce its magic step by step as you need it.

Bean construction:


def testBean = new Customer(fname: "Bob", sname: "Newt", age: 42)
// Java: c = new Customer(); c.setFname("Bob"); c.setSname("Newt"); c.setAge(42);


(Of course this starts to pay of if either you don't want to create a constructor or if there are "many" properties and you need to set different subsets of them (constructor with 4+ arguments is hard to read).)

Reading a file:


assert test.method() == new File("expected.txt").getText()
// Java: buffered reader line by line ...; Note: == actually uses equals()


Checking the content of a collection/map:


assert customerFinder.findAll().collect {it.sname}.sort() == ["Lizard","Newt"]
// Java: too long to show here (extract only surnames, sort them, compare ...)
assert getCapitalsMap() == ["UK" : "London", "CR" : "Prague"]


Regular expressions:


assert ("dog1-and-dog2" =~ /dog\d/).getAt([0,1]) == ["dog1", "dog2"]

Continue reading →

Comparison of Eclipse 3.6 and IntelliJ IDEA 10.5: Pros and Cons

After having worked with Eclipse for over 5 years I've came to use IntelliJ IDEA intensively on a J2EE project in three months and took this as an opportunity to compare the two. You can't really compare 5 years and 3 months but I still believe that it is long enough to get a pretty good overview of what a tool is like.

For the impatient:

IntelliJ is a very good tool, its killing feature for me is its excellent support for other languages such as Groovy (e.g. for unit tests) and Clojure. Many details are more worked-out and with a higher usability then in Eclipse, f.ex. search & replace with match highlighting and replacement preview. Its support for navigability and refactoring across multiple languages (Java, JSP, JSF, HQL, Spring config in my case) is also an absolutely great feature for productivity. And of course I have to add it credits for being a Czech product [1] (interestingly enough, NetBeans also comes from the Czech Republic [2]; it's a pity Eclipse hasn't this link too) :-).

My main issue with IntelliJ is its performance. First, running tests is slow because IntelliJ only does (re)compile the test/source when you hit the run button as opposed to Eclipse' incremental compilation. And that makes TDD very painful. (I tried to use the old Eclipse Mode plugin but it has problems with IntelliJ 9/10.) Second, sometimes the UI freezes* and you have to wait seconds or tens of seconds for it to respond again (even after disabling most plugins and some analysis). It doesn't happen too often but often enough to be noticed, to be annoying, and to interrupt the development flow.

*) Update: UI freezes may be a specific issue of Mac 64b 1.6 JDK

So I guess I'll use either Eclipse or IntelliJ with respect to the needs of the project at hand and hope for IntelliJ to resolve its performance issues (as NetBeans did).
Continue reading →

Intro: Java Webapp Monitoring with Hyperic HQ + How to Alert on Too Many Errors in Logs

This post describes how to set up the Java-based open source monitoring tool Hyperic HQ to monitor application server error logs and send a single warning e-mail when there are more of them than a threshold. In the previous post Aggregating Error Logs to Send a Warning Email When Too Many of Them – Log4j, Stat4j, SMTPAppender we've seen how to achieve that programatically while this solution is just about configuration. We will also see a little what else (a lot!) Hyperic can do for you and what the impressions after a short experimentation with it are.
Continue reading →

hasProperty, the Hidden Gem of Hamcrest (and assertThat)

If you got used to JUnit 4's assertThat
Continue reading →

Aggregating Error Logs to Send a Warning Email When Too Many of Them - Log4j, Stat4j, SMTPAppender

Our development team wanted to get notified as soon as something goes wrong in our production system, a critical Java web application serving thousands of customers daily. The idea was to let it send us an email when there are too many errors, indicating usually a problem with a database, an external web service, or something really bad with the application itself. In this post I want to present a simple solution we have implemented using a custom Log4J Appender based on Stats4j and an SMTPAppender (which is more difficult to configure and troubleshoot than you might expect) and in the following post I explore how to achieve the same effect with the open-source Hyperic HQ monitoring SW.


Continue reading →

Spring: Make an Externally Created Object Available to Beans in applicationContext.xml

If your Spring beans need access to an object that is not created by Spring itself, you can "inject" it into the context by using a static parent context and registering the object with it. Beans can then reference it just as if it was defined in the application context file.

Java: Configure ApplicationContext with an Injected Bean


Continue reading →

Tools for Renaming the Package of a Dependency with Maven

If you need to rename the Java package of a 3rd party library, e.g. to include it directly in your project while avoiding possible conflicts, you can use one of the following Maven plugins (and they may be more) in the package lifecycle phase:
  1. Uberize plugin (latest - org.fusesource.mvnplugins:maven-uberize-plugin:1.20) - originally inspired by the Shade plugin, intended to overcome some of its limitations. Intended primarily to merge your code and dependencies into one jar.
  2. Shade plugin
  3. package-rename-task, Ant-based Maven plugin - I'm not sure whether this is further maintained

Continue reading →

Note to Self: Running GroovyConsole with a Maven Project's Classpath

It's pretty useful to have the ability to eperiment interactively with some API using the (desktop) Groovy Console
Continue reading →

Most interesting links of September

Recommended Readings


Continue reading →

Inspect Your Webapp in a Live Environment Interactively with GroovyConsole

Have you ever needed to check the state of your webapp's objects/Session/.. to find out why the hell something doesn't work or have you had to learn a weird 3rd party API that is only available on the server? Then you were doomed ... until the publication of GroovyConsole. JeeUtils GroovyConsole provides a JSP page that let you execute any Groovy/Java code on the server side, with access to server-side objects like request/session etc.

Here is a screenshot of my recent troubleshooting session, where I needed to check the state of a session-scoped JSF Managed Bean:


Continue reading →

Copyright © 2024 Jakub Holý
Powered by Cryogen
Theme by KingMob