Note: This project is currently in a work in progress so not all languages or sections are complete.

Test Driven Development with Java

Installing Homebrew

We're going to start by installing Homebrew which will make installing everything else we need much easier.

Open a Terminal window and run the following commands:

1
2
xcode-select --install
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Installing Java

Now we can easily install Java with Homebrew using the following:

1
brew cask install java

Creating the Project

Now we'll use Savant to initialize a project for us.

1
2
3
brew tap spilth/tap && brew install savant
savant init avajay -l java
cd avajay

Dependency Management

When building software you will frequently use libraries and tools from a third party. Since they have their own development lifecycles and versions we want to be able to define a specific version of that dependency to use in our software. We want to do that with a tool and a file.

For Java we'll use the tool Maven and our dependencies will be defined in the file pom.xml.

1
brew install maven

Adding a Testing Library

We're going to use the testing library JUnit to write our tests.

Edit the file pom.xml and add JUnit as a testing dependency:

1
2
3
4
5
6
7
8
<dependencies>
  <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
  </dependency>
</dependencies>

Then we retrieve JUnit by running mvn dependency:resolve.

Finally we initialize JUnit by running mkdir -p src/test/java/tdd.

The First Test

Create the file src/test/java/tdd/PiglatinTest.java with the following contents:

1
2
3
4
5
6
7
8
9
10
package tdd;

import org.junit.Test;

public class PiglatinTest {
    @Test
    public void translateWord_startingWithVowel() {
        assertEquals("apple", Piglatin.translateWorld("appleyay"));
    }
}

Then run the test with the command mvn test to see the results:

1
2
3
4
5
6
7
8
9
[INFO] Compiling 2 source files to /Users/bkelly/temp/piglatin-java/target/test-classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/bkelly/temp/piglatin-java/src/test/java/tdd/PiglatinTest.java:[9,32] cannot find symbol
  symbol:   variable Piglatin
  location: class tdd.PiglatinTest
[INFO] 1 error
[INFO] -------------------------------------------------------------

Comments