Getting started with Spock

Spock is a testing framework. You write tests in Groovy, which results in less code that is more readable. Good!

I first heard about Spock on Communities in Action and wanted to take it for a test ride. The problem was that I had some trouble getting started as the documentation seemed to be a bit outdated. Here’s a short summary of what I had to do.

The first obstacle was finding a binary download. I ended up grabbing one from their build server.

The next step is adding the spock-core-*.jar to your project and enable groovy support. (In Intellij I got a “dialog” in the top of my groovy file saying that I had to configure the Groovy SDK.)

Next up is adding a new test class and extend spock.lang.Specification. When the test is written, you can run it as a regular JUnit test.

Sweet!

Here’s a simple example

class GLMathTest extends Specification {  

  def "multiplying 4x4 matrix"() {
    given:
    float[] m1 = [
      1, 0, 0, 0,
      1, 1, 0, 0,
      1, 0, 1, 0,
      1, 0, 0, 1,
    ]
    float[] m2 = [
      1, 5, 9, 13,
      2, 6, 10, 14,
      3, 7, 11, 15,
      4, 8, 12, 16
    ]

    when:
    float[] result = GLMath.multiply4x4(m1, m2)

    then:
    result == [
      28, 5, 9, 13,
      32, 6, 10, 14,
      36, 7, 11, 15,
      40, 8, 12, 16
    ]
  }
}

Resources
Spock – http://code.google.com/p/spock/
Tutorial #1 - http://tv.jetbrains.net/videocontent/getting-started-with-spock-and-groovy
Tutorial #2 –  http://tv.jetbrains.net/videocontent/spock-and-mock-object-basics

Scalatra sample application

A lot has happend since last time I wrote a post. I’ve moved to Oslo, and started working at Bouvet. Which I’m very pleased with!

Recently I gave a short introduction to Scalatra at one of our big internal competence events. The slides weren’t that good, and in norwegian, so I’m not planning on publishing them. Anyway. While working on my presentation I ended up writing some sample applications upon github. They’re available here.

Mini “discovery”: how to run all tests from within Eclipse!

For quite some time I’ve been unaware of the possibility to run all JUnit tests from within Eclipse. I thought the only way it could be done (besides using Maven etc) was to manually create test suites. What I’ve done “wrong” is just doing a “Run as JUnit test” on the packages. Turns out you can also do thins on a source folder, causing every JUnit test in that folder to execute! :)

Becoming test driven – the first steps

TDD. The most common meaning of this abbreviation is probably Test Driven Development or Test Driven Design. Simply put, it’s all about writing test code before writing production code. Why would one like to do that, you may ask? The answer is simple; your code will eventually become a lot better and easier to maintain. Not only for yourself, but for everyone that have to understand and work with your code. I won’t write a lot about pros and cons, or what it is (Check out the link in the final paragraph!). I’ll just list a few pointers to how to get started and how to get better. I myself can barely claim to perform TDD, but I strive to get there! So..I don’t claim to be an expert, I just want to do some TDD advertising ;)

Unit tests
The first thing to do is to actually learn how to write unit tests, and how to do it right. When I first tried to do some work using TDD, after a while I figured out that my tests weren’t that good. I thought I knew what a unit test was and that I could jump right into it. Turned out that I had some things to learn :) What’s a mock? Or a stub? What is the difference between a unit test and an integration test? What is meant by Inversion of Control / Dependency Injection? You’ll find answers to all of these questions by doing a little bit of Google magic. Still, I want to recommend The Art of Unit Testing by Roy Osherove. Though the examples are done using C#, everyone will make use of this book. This book will teach you a lot about unit testing!

Test first
A common problem with unit tests is that the production code is hard to test. There can be many reasons for this, and I guess the most common is dealing with dependencies. Though there are many factors that can affect the testability of code, a common divisor is that code that is hard to test is bad code. One of the advantages when writing the test on beforehand is that you are forced to write the code in a way that is testable! This can be quite difficult to get started with (at least I think it is/was). The only thing to do is practice. Of course, you should also read up a bit on the topic, but in the end I think it’s all about practice. And if not able to write the test up front, at least write it while you are working on the code . The book Test Driven Development: By Example by Kent Beck is highly recommended!

Kata
One way to practice TDD is to perform so called code Kata‘s.  These are exercises that are meant to be done repeatedly. In addition to practicing TDD and test first thinking, you will become better at using your IDE. Some Kata’s that I know of are string calculator and bowling game.

Inspiration
There is a lot of good resources, books and blogs with content related to TDD. “Uncle Bob” has done a lot of  amazing presentations. and I suggest checking out this one (if you’re in a hurry, jump to ~23:28). I bet it will motivate you to start doing test driven development!

Michael Feathers visited Kristiansand

This evening Michael Feathers gave a talk at javaBin Sørlandet, the local Java user group. Michael Feathers is a “programmer celebrity” and is perhaps most known as the author of the book Working effectively with legacy code, the author of the C++ unit testing framework CPPUnit and for being one of the Object Mentor‘s.

I’m actually reading the book at the moment, and I find it very good and interesting. Put shortly, it will teach you how to add features to an existing code base (that is not in test harness) in a good way. It contains a lot of typical questions with good answers. Really a lot of useful tips and tricks that will make you a better programmer, and less painful to work with legacy code!

The talk Michael Feathers gave was not on legacy code, but on the synergy between testable code and good design, and it was indeed very interesting! Code that’s hard to test, is most likely hard to test because the design isn’t that good. For instance, a widely asked question is how to test private methods. There are lots of answers to this, but one of the solutions to his example was to extract the code into a new class. The reason for this was separation of concerns. By following the Single Responsibility Principle (SRP), we get classes that in most cases are easy to understand, and also easy to test. Also, as he quoted Robert Martin (Uncle Bob) on that when a class has a single responsibility, there is only one reason for it to change.

Feathers also drew a line from how software design got better when separating the concerns and making more, but simpler classes, with how our brain is working and how we find it easier to understand and remember things when they are less complex. Two dependencies are way better than five!

Another good point (based on a quote from some guy I don’t remember the name of) was that the people that find simplifying a system unnecessary is most often the system expert. The guys who live in the code base all day long, and now every corner of it. Though this may be OK for them, a developer that never has seen the code before will most likely have to spend hours, days, weeks or months in it before her/she gets a good overview and gets comfortable adding features or making changes. It’s clearly that a simpler design is a better design!

Disclaimer:
This is not meant to be a complete summary of the talk that was given on today’s meeting, but more like a teaser for you, and note to self for me ;-) I might as well also have expressed something in a different way, and not necessariliy 100% correct. But anyway, it was fun to attend, and I’ll continue on my path towards becoming better at TDD and good design.

Groovy++ ?

Just a short Sunday blog post :-)

I just noticed a link popping up on Twitter from @DZone with the message; “Will Groovy spell the end of Scala?”. Following the link it turned out that it actually wasn’t Groovy, but Groovy++. Groovy++ introduces static typing without losing the dynamic benefits and powers. Read more in the blog post and also check out this article on Groovy++.

In the blog post there is also a link to a podcast show named Illegal Argument. This show is discussing topics related to Java and the JVM. I haven’t listened to it yet,  but I will!

Getting Groovy

Lately I’ve tried out the Grails framework a bit for a little pet project. It started with a little peek on Groovy, and then after a little messing around with the “getting started” part, I wanted to check out grails as well. I must say it was very pleasant to work with!

Though it was a very little project I did with Grails, I think ihas potential. I really like the way everything is done by convention, and the plugins just makes it incredible simple to have a lot of functionality up and running in no time! Security, searching and JMS just to mention a few. Check out the plugin portal if you are curious. One more thing I find cool is that you can run Grails applications on Google App Engine. This is done very easily by using a plugin!

I also noticed a project named Griffon which is a Grails like framework for developing desktop applications in Groovy. I haven’t tried it out, but it seems interesting. As I read about Griffon I also got aware of the UI toolkits SWT and Pivot. Frankly I did only know of AWT and Swing, but the next time I decide to write a GUI app in Java or Groovy, I’ll definitely consider trying out one of these :-)

Finally, some groovy and grails resources.

http://grailstutorials.com – The design is crap, but there are a lot of tutorials)
http://grailspodcast.com/blog/list – Interesting podcasts with the latest grails/groovy news
http://goo.gl/uTEM – An article on groovy meta programming (there’s a lot of groovy stuff on the same site)

BDD – Behaviour Driven Development

When I first was reading about Behaviour Driven Development, I just thought of it as a different way of naming tests. Just giving the test a name that describes the behaivour that it will cover. This is not exactly right for what I’ve learned now. I might write more about it later, but for now I’ll just list a couple of resources that I’ve found.

What exactly is BDD?

Read Dan North’s intorduction here. Also, you should take a look at Rob Conery’s introduction screencast.

Frameworks

To get the most out of BDD I think a framework is necessary. There exist a lot of frameworks that let you write a textual specification of features/scenarios. The framework then analyse them and require you to write a set of test to cover what you’ve specified and give you output telling you if the tests are failing or successful. This way you get a test suite that’s readable for a person that don’t know anything about programming.

The first framework I ever saw in action is JBehave (note that the actual navigation is way down at the bottom of the page(!?)). This also have a .NET implementation called NBehave. I started out with JBehave, but as I didn’t find that much documentation for it, I started looking for alternatives. I then came over Cucumber. This is a Ruby framework which seem to be used widely, and also have a lot of documentation and examples. Though this is a Ruby framework, it is possible to use it with a lot of different languages. For instance cuke4duke and  JRuby opens the door to a lot of languages running on the JVM, and there is also a .NET version called cuke4nuke.

Currently I’m trying out cuke4duke with Java. I found the examples very helpful to get started with Java and Maven

Tomcat + Apache (+ Grails)

I’ve spent quite some time on deploying my first grails application to a Tomcat server, and get the setup just the way I want it. I thought that writing a small tutorial on how to do it was a good idea, as I then have it for later use, and perhaps someone else can have good use of it. The grails part of this is not very important, as it will be just the same for Java applications. I don’t claim this to be the ultimate(or even correct) setup, but at least it is working the way I want it to. Feel free to comment!

Deploying a grails application to Tomcat is actually quite easy. Just create a war file, and place it in the webapps folder.

To create a war with production environment settings issue the command

grails prod war

When placing this in the webapps folder, Tomcat will automatically unpack the war to a folder with the same name. You can access it at http://server.address:8080/appname (8080 is the default listen port). For some cases this might be good enough. If you on the other hand want to access the webapp without having to specify both the port number and the application name, you want some kind of virtual hosting.

In my case I wanted to access the application from a domain name. I don’t have much experience with either tomcat or apache configuration, but I knew how to set up a name based virtual host on apache. Name based means that Apache interprets the incoming request and decides what to serve it based on the domain name. In addition to this we can also set up a name based virtual host on Tomcat. Having this we just need some kind of connection between Tomcat and Apache. This way Apache becomes the entry point, while Tomcat is the application server. Let’s start!

In this example I’m using a Ubuntu server, Tomcat 6.0 and Apache 2.2

Set up a virtual host in Apache and load the necessary modules

Create a new file in /etc/apache2/sites-available/ and name it after the domain name. Edit it, and write something like this:

  <VirtualHost *:80>
    ServerName domain.com
    ProxyPass / ajp://localhost:8009/
  </VirtualHost>

This will redirect all incoming requests for domain.com to Tomcat. AJP is a protocol used to connect Tomcat and Apache, and 8009 is the default port. Read more here or google it. AJP depends on the mod_proxy, but (at least on my system) when you enable mod_proxy_ajp mod_proxy will be enabled automatically.

sudo a2enmod proxy_ajp

When we’re at it, you also have to enable your new site (the one we defined in sites-available)

sudo a2ensite name-of-site (the filename you chose some steps ago)

Note that it now also is listed under sites-enabled. Now we’ll continue with configuring Tomcat.

Tomcat configuration

There isn’t too much to be done with Tomcat. Open server.xml in <tomcat-dir>/conf/. First find the AJP connector line, and uncomment it if it’s currently active. Then scroll to the bottom, (or wherever your </Engine> tag is. Inside it add a new name basd host like this:

 <!-- Uncomment this line -->
 <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

 <Engine>
    <!-- *snip* -->
    <Host name="domain.com" appBase="webapps/appName">
        <Context path="" docBase="." />
    </Host>
  </Engine>

Now we’re ready, and hopefully everything works! Remember to restart both apache and tomcat!

Resources

http://oreilly.com/java/archive/tomcat-tips.html