Skip to content
Harry Cummings edited this page May 10, 2017 · 14 revisions

Tests are a very important communication tool and I want to write tests in a way that allows me to communicate as clearly as possible. I've found the RSpec style of testing (also found in the JavaScript test frameworks Jasmine and Mocha) to be particularly flexible and expressive.

Two key features of this syntax make it possible to write much more descriptive tests with richer contextual information:

  • Test names are strings and don't have to be valid method/function names
  • Tests can have a nested structure rather than being a flat list of methods

I wanted to have the same benefits when writing tests on Java projects.

Scope

The intent is to keep this library very small, both by leveraging existing frameworks and providing an open mechanism for extensibility.

Building on other frameworks

JarSpec relies on JUnit for execution and reporting/tooling, and does not attempt to provide its own solution for assertions or test doubles. Users of JarSpec are free to pick whichever libraries they prefer, using standard JUnit or Hamcrest assertions and matchers (which are included by default as a transitive dependency), and/or pulling in whatever other libraries they prefer to use (such as Mockito for test doubles).

Extensibility

JarSpec supports the use of mixins for implementing new features without modifying the core library. This allows more esoteric use cases to be supported without cluttering the implementation of mainline features.

Alternatives

There are frameworks for other JVM languages that support this kind of syntax. RSpec itself of course could be used on the JVM thanks to JRuby, ScalaTest also supports this through its FunSpec class, and Spek (Kotlin) follows a similar philosophy. I don't like to introduce extra languages to a project without good reason though, and I thought Java 8 should be up to the task on its own.

It is possible to write nested test classes with JUnit, for example using junit-nested or the experimental Enclosed runner. This provides some of the benefits found in RSpec, but not all.

The Gherkin language obviously places human-readability first, and there is a Java implementation of Cucumber, which I do use and enjoy. However, I think the use case for Gherkin and Cucumber is more business-facing tests, and I wouldn't want to use them for my day-to-day unit tests, which should serve developers first (both as the people who have to write them and as the audience).

Finally, both Jnario (based on Xtend) and Spock (based on Groovy) offer their own variations on the various BDD-style syntax options mentioned above. While these frameworks definitely allow for more expressive tests, Jnario is quite closely tied to (thought not strictly dependent on) Eclipse, and Spock's syntax doesn't provide the same benefits as those mentioned for RSpec above.