Upgrading Maven from 2.0.x to 2.1.x – profiles.xml

October 26, 2009 Josh Leave a comment

When we tried to upgrade from Maven 2.0.x to 2.1.x, our build broke, indicating we had a problem with our profiles.xml. I had a hard time finding out what’s supposed to be in the profiles.xml, since I couldn’t find a reference to the schema on the Maven website.  I finally found a profiles.xml in one of our projects at work that referenced the profiles XML schema, which can be found here:

http://maven.apache.org/xsd/profiles-1.0.0.xsd

I’m still not sure if the schema changed from 2.0.x to 2.1.x, but I know that using <profiles/> as the root element worked in 2.0.x but did not work in 2.1.x.  When you upgrade to 2.1.x, make sure the root element in your profiles.xml is <profilesXml/>. Actually, you can make the change to your profiles.xml before upgrading to Maven 2.1.x and then upgrade when you’re ready.

Categories: Maven Tags:

Mocking and stubbing in Groovy with ‘with’

October 5, 2009 Josh Leave a comment

I often use metaClass in Groovy to create mocks or stubs in my unit tests. Recently I’ve discovered that the with method makes this a bit simpler.

This:

Foo.metaClass.with {
  doSomething = {
    return true
  }
  anotherThing = {foo ->
    assertEquals 42, foo
  }
}

is slightly shorter than this:

Foo.metaClass.doSomething = {
  return true
}
Foo.metaClass.anotherThing = {foo ->
  assertEquals 42, foo
}

and less code means less bugs.

[Update: For more explanation of why the with method is so great, read this post.]
[Update: And for another way to write your mocks and stubs, see my previous post on mocking with Groovy.]

Categories: Groovy, TDD Tags: , ,

Integrating Unit Tests

August 19, 2009 Eric Leave a comment

There’s been a lot of talk about TDD, Responsibility Driven Design, and what constitutes a unit test versus an integration test this week at work.  It got me thinking about the definitions.  I used to think it was very clear cut. Unit tests isolate a single class, integration test don’t.

Is the line so simple though?  What about a unit test that tests a method that uses other methods within the same class to get its work done.  Is testing the results of that method a unit test?

For example:

// Say I wanted to test the method.
String makeDeposit( String xmlData ) {
def transaction = parseRequestXml( request )
def receipt = bankBusinessObject.deposit( transaction )
return makeResponseXml( receipt )
}

To be a unit test, I should at least mock the bankBusinessObject, and should probably ask the Mock to fail my test if the deposit method isn’t called.

But, it seems that to be a true unit test for makeDeposit, I should also mock parseRequestXml and makeResponseXml. And, for the makeDeposit unit test, rather than test that you get the expected xml repsponse data given the controlled input data, just ensure that makeDeposit calls parseRequestXml to parse it, bankBuisinessObject.deposit to act on it, and makeResponseXml to marshal the results.

I did some brain storming and came up with a new classification scheme for organizing my tests.

Unit

  • Macro Unit Tests – Tests isolated to a single class.  This is where you’d see testing of methods which call other methods to get some of their work done.
  • Micro Unit Tests – Tests isolated to a single method.  Completely test the method in isolation, mocking as necessary.   If you work in a language like Groovy and want to unit test a method that calls or depends on other methods in the same class, mock the dependent methods individually and have the mocks fail the test if they’re not called as expected, in the order expected.  I’m not sure if that is possible in Java.  (Maybe with some sort of test harness with AOP involved to intercept the method calls during the test??)

Integration

  • Standard Integration Tests – Integration tests that span other methods, classes, depend on other services, databases, etc.
  • Requirements Tests – Tests for those when you want to test a specific requirement or bug fix.  Very helpful when something changes later that breaks the bug you fixed a few releases back.  Or when the customer opens a ticket asking for functionality that contradicts a previous request.

Thoughts?

Java 6 and Maven on Mac OS X Leopard

August 12, 2009 Josh 2 comments

This morning I was having problems with Java and Maven on my Mac. I had my JAVA_HOME set to /Library/Java/Home, which was pointing to Java 6. When I ran mvn -v, Maven told me it was pointing to Java 5. I couldn’t figure out what was wrong because running java -version showed me Java 6.

The solution, which I found in this post, was to set my JAVA_HOME to the actual place where Java is installed, which is something like:

/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home

This worked for me, but YMMV.

Categories: Java, Maven Tags: , ,

Who needs a mock framework?

July 26, 2009 Josh 10 comments

In Groovy, you can create mocks & stubs using native language features, so you can forget about learning a mock framework.

class Author {
  def getName() {
    return 'Josh Brown'
  }
  def isFamous() {
    return false
  }
}

Let’s stub the isFamous method:

def author = [isFamous: {true}] as Author
assert 'Josh Brown' == author.getName()
assert author.isFamous()

(If you haven’t already, stick the above code in your groovyConsole, run it, and play around with it.)

When mocking and stubbing are so easy to do with the language itself, using a mock framework is overkill.

[Update: Bob Martin recently wrote an excellent post about Manual Mocking.]

Categories: Groovy, TDD Tags: , ,

Story time with easyb

January 27, 2009 Josh 2 comments

Everyone loves a good story.
 

Star Wars Trilogy

 

With easyb, you can write stories in your code!

scenario "the Death Star destroys Alderaan", {
    given "the Death Star", {}
    and "Alderaan", {}
    and "Alderaan is targeted by the Death Star", {}
    when "the Death Star fires", {}
    then "Alderaan is destroyed", {}
 }

You probably could’ve written that with the stakeholders yelling over shoulder. No – the Death Star should destroy Yavin IV, not Alderaan!!! If you’re writing readable code in front of them, you might be able to get them to make a decision while you’re at your keyboard.

Now you have executable documentation, and the stakeholders can leave the party. And once they’re gone, you can move on to writing some Groovy code to fill in those empty squiggly braces:

scenario "the Death Star destroys Alderaan", {
    given "the Death Star", {
        deathStar = new DeathStar()
    }
    and "Alderaan", {
        alderaan = new Planet(name:"Alderaan")
        Galaxy.planets << alderaan
    }
    and "Alderaan is targeted by the Death Star", {
        deathStar.target = alderaan
    }
    when "the Death Star fires", {
        deathStar.fire()
    }
    then "Alderaan is destroyed", {
        Galaxy.planets.shouldNotHave alderaan
    }
}

Now run it and watch it fail. Ah, the joy of xDD…

From here, you can write the DeathStar, Planet, and Galaxy classes you need to make it pass. Run it again! Refactor! Repeat!

Now you have documentation that’s readable, executable, and verifies that your code does what it’s supposed to do! Wasn’t that easy?

Categories: Groovy, TDD Tags: , , ,

[].inject(“Groovy”){}

January 25, 2009 Peabody 5 comments

The collection helper methods like each, findAll, and collect are among the clearest productivity advantages of Groovy over Java. For reference, here’s a list of the common collection helper methods on the Groovy Quick Start page (after opening the link you’ll have to scroll down to them).

The inject method is among the most interesting of them all but is not utilized often by Groovy developers. It’s useful but somewhat difficult to understand, relative to the complexity of the other collection helper methods, so many developers get the job done without inject and never bother to learn about it. I encourage everyone to learn inject so that they can understand another approach for attacking their problems and choose the most appropriate approach. The inject method is also a great first step in learning a little about functional programming.

Functional Style – A stork story for inject
The Scala and Clojure languages on the JVM have aroused interest in functional style programming. Even with an imperative language like Java we can alter our programming style to more of a functional one, so learning the functional tenets can be very valuable to your arsenal.

Let’s take some Groovy code that calculates the sum of numbers 1 through 10.
def total = 0
(1..10).each{total += it}
return total

Here we apply a closure to each value in the 1..10 range. But as we repeatly apply this closure we also need to keep track of a total variable, which changes with each iteration.

In pure functional programming variables are… not allowed. This poses an interesting twist to our problem. How can we accomplish the same functionality as the above code without any variables?

The answer to most “How can I solve this without variables?” questions: Recursion.

Let’s examine how we totaled up values 1 to 10:
(((((((((((0)+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)
Each set of paranthesis describes the value of total at some given point in time starting with 0 and expanding out to its final result of 55. Consequently, total gets set to 11 different values over its lifetime and only the last of those 11 was actually what we wanted.

The other danger here is that another developer might “refactor” your code by moving all variable declarations to the top of methods. I’ve inherited Java code like this quite often, where the beginning of some ginormous method sets a bunch of values like total = 0, even though taking the initializing value out of context actually makes the code more confusing.

With inject we can make the value of total clearer by keeping the calculation within the scope of its declaration. We “inject” the initial value of 0 and at each iteration the previousResult value represents what used to be represented by a waffling total variable.
def total = (1..10).inject(0){previousResult, iterationValue ->
  previousResult + iterationValue
}

The concept of inject in Groovy is identical to that of a left fold in functional programming. Ironically, the Groovy’s implementation of inject does not use recursion for, what I’m assuming, are performance reasons.

sum()
We’ve been using a very simple example. Those familiar with Groovy might ask why not just use the sum() method available to lists:
(1..10).sum()

Well, I’m glad you brought it up because there’s more to sum() than you may have realized.

You see, sum() allows you to “inject” an initial value.
(1..10).sum() // 55
(1..10).sum(0) // 55
(1..10).sum(3) // 58

This doesn’t seem incredibly valuable at the surface, but let’s look at why it can be.

Try calling sum() on an empty list:
[].sum() // null

Yes, the result is null. Most folks would assume that the result should be 0. So why isn’t the result 0? You have to realize that the sum() method merely requires that the objects in the list have a plus() method, which means that Groovy’s sum() method can’t assume that the empty list you passed in held Integer values.

For example, you could join strings in a list using sum():
["strings ","in ","a ", "list "].sum() // "strings in a list"

If you had an empty list intended for Strings, a sum() of 0 doesn’t make sense – an empty String would be more appropriate, so use sum(""). If you don’t “initialize” a value into sum() you could end up with null if your list is empty and that could break some assumptions in your code, leading to a NPE. It’s often a good idea to “initialize” the sum() method with a value, much like you would do with inject().

inject() to build collections
Java programmers switching to Groovy often use each{} for everything involving iterations. They write the equivalent of an imperative Java for loop:
def oneToTen = (1..10)
def doubles = []
oneToTen.each{myValue->
  doubles.add(myValue*2);
}
return doubles

They’re often thrilled to find out that using a different collection helper method makes their code more readable and concise:
def doubles = (1..10).collect{ it*2 }

Always scan your Groovy code for a collection helper method code smell:
If your each{} or other collection helper method (findAll, collect, etc.) has a variable declaration in the line before it, you’re likely to benefit by using a different method.

I usually play around in the GroovyConsole (just type groovyConsole in your command line if you have Groovy installed) to decide which collection helper method does the job best. It’s a fun challenge to include inject into the mix even though it has only emerged once as the victor in my production code… and honestly I can’t remember what that was and I don’t have access to the code any more. Bummers.

There’s an inject example at the bottom of a post we made on chaining and currying closures back in November ‘08. Chris made a clever improvement in the comments section of that post as well. Thanks for that, Chris! We greatly welcome any improvements or questions here and we hope to see even more in the future from our readers.

Categories: Groovy Tags: , , ,

Liferay Portal is pretty snazzy

January 13, 2009 Peabody Leave a comment

I’m a big fan of technologies I can play with quickly, without having to journey to Mordor or wave dead chickens over glyphs in the sand. Basically, I hate setting up environments. I had this running quickly. Yay for me.

I’m sitting in the evening COJUG (Central Ohio Java User Group) session given by Ayan Dave of Quick Solutions on the Liferay Portal product. I almost didn’t come. Virtually every developer I know that’s worked on a portal project hated it. I think some of them even had the project scrapped.

I hear “portal” and I want to run the other way.

But I’m being brave tonight. Luckily, it was free and very simple to get started with Liferay Portal. It comes prepackaged with one of many choices of servers. I chose Tomcat.

I started up the instance of Tomcat and opened my browser to http://localhost:8080/

A login screen. I created my own account but didn’t seem to have permissions to do anything… went back to the getting started guide (link above) to find I could log in as test@liferay.com with a password of test… that seemed to give me admin privileges.

In no time I could drag and drop the couple of default widgets. That was kinda gratifying.

At the top-right is a dropdown menu. Select Add Application. You’ll get a nice selection of already developed portlets. I chose Finance > Stocks. Played around with it. Pretty stinking cool.

Try it out yourself. Have fun!

Thanks to Ayan for presenting at COJUG tonight.

PS – I also had cake tonight. The cake is not a lie!

Categories: Uncategorized