In my previous post I included some code to get the currently logged-in user. This code was copy-and-pasted from the sample applications provided in the SDK. Let’s consider this previous code to be a prototype. Real software development should always be test-driven, otherwise it’s just an exercise in building legacy code.

I’ve heard good things about two Scala based testing frameworks: ScalaTest and Specs. After some investigation into both I’ve decided to run with Specs. I intend to test in a behavioural manner and so don’t need the flexibility of other testing styles that ScalaTest provides. In my opinion Specs facilitates a cleaner testing style and has really wonderful integration with my preferred mocking library, Mockito. In the end it’s really just a matter of personal preference.

The static call

My first challenge to overcome is the static method call to the Google App Engine’s UserServiceFactory:

UserServiceFactory.getUserService

As it stands, the LoginSnippet object is untestable without including a mocking framework that supports the mocking of static method calls. Whilst Mockito provides simple and elegant mocking, it does not support the mocking of static method calls.

A quick introspection into the UserServiceFactory shows that (as of v1.2.0) the factory method is simply:

return new UserServiceImpl();

But it would be a bad idea to replace the current call to the factory with this instantiation because:

  1. it may not be backwards compatible as the GAE SDK is updated;
  2. it may not be the same implementation once deployed to the service; and
  3. it simply doesn’t work (UserServiceImpl is package private).

At this stage I’m forced to modify my class to facilitate my test. The primary constructor is modified to take an injected UserService. (It makes me cringe a bit to do this, but can it be done without using AOP or a different mocking library? Please fill me in on the secret if you know how).

 1: class LoginSnippet(userService: UserService) {
 2:     def this() = this (UserServiceFactory.getUserService)
 3:     def render(request: _root_.javax.servlet.http.HttpServletRequest) = {
            ... function continues as per my previous post ...
14:     }
15: }

The class definition on line 1 provides a new primary constructor. It now takes a UserService parameter. On line 2 a zero-arg constructor is defined that delegates to the primary constructor. There’s nothing particular to Scala in this scenario. However, it is worth noting that the execution of UserServiceFactory.getUserService now occurs in the constructor. If I needed it to continue to be executed in the render function I could do the following:

 1: class LoginSnippet(getUserService: => UserService) {
 2:     def this() = this ({UserServiceFactory.getUserService})
 3:     def render(request: _root_.javax.servlet.http.HttpServletRequest) = {
 4:         val userService = getUserService

The distinction here is that the constructor now takes a parameter which implies (=>) a UserService. It may be a literal UserService instance (as our test-time mock would be), or it may be a code block that returns a UserService, as can be seen on line 2 (note the added curly braces). If a code block is passed, it will not be executed until invoked on line 4.

Running Specs with Mockito via Ant

As is stands, there is currently a small trick to getting Specs running via Ant. It is clearly documented on their site, but I sometimes have a blind spot when it comes to RTFM’ing. Here it is in a nutshell:

1: import org.specs.Specification
2: import org.specs.mock.Mockito
3: import org.specs.runner.JUnit4
4: class SnippetSpecs extends JUnit4(snippetSpec)
5: object snippetSpec extends Specification with Mockito { ... }

The Specifications must be defined in an object (line 5), but the JUnit Ant task will require a class instance (line 4). The class must be something that JUnit knows how to run and so must extend the Specs JUnit4 runner. Finally, the addition of the Mockito trait (line 5) provides syntactic sugar to sweeten the mocking experience.

In the Ant build.xml the specs are executed with the junit task. The batchtest fileset should include the classes (in my case *Specs) and not the objects (*Spec).

Testing the sign-in snippet with mocks and XML matchers

The sign-in snippet should be shown when we don’t have a currently logged-in user. This forms the basis of my first specification. The task seems simple – ensure the user is null and assert the correct XHTML is returned.

1:  "LoginSnippet with an unknown user" should {
2:      "Provide a login prompt" in {
3:          userService.getCurrentUser returns null
4:          request.getRequestURI returns "requestURI"
5:          userService.createLoginURL("requestURI") returns "loginURL"
6:          val xhtml = snippet render request
7:          xhtml must ==/(<p>Hello! <a href="loginURL">Sign in</a> just for kicks.</p>)
        }
    }

The specification is described on lines 1-2. The mock expectations are established on lines 3-5 (notice how clean the syntax is, thanks to the Specs’ Mockito trait?). The code under test is executed on line 6. The expectation is asserted on line 7.

The expectation makes use of one of Spec’s XML matchers. Matchers are powerful tools for asserting only the aspects of the comparisons that are relevant. In this case, the must ==/ matcher compares the equality of a node sequence whilst ignoring whitespace.

Testing the sign-out snippet – splitting hairs over Atoms

The sign-out snippet seems equally as straight-forward, but there is a catch. My first approach was:

1:  "LoginSnippet with a known user" should {
2:      "Provide a logout prompt" in {
3:          val user = new User("x", "y")
4:          userService.getCurrentUser returns user
5:          request.getRequestURI returns "requestURI"
6:          userService.createLogoutURL("requestURI") returns "logoutURL"
7:          val xhtml = snippet render request
8:          xhtml must ==/(<p>Hello, x! Now you can <a href="logoutURL">sign out</a> again.</p>)
        }
    }

This specification fails! The XML on line 8 seems to be what we are receiving, but the equality matcher failed. After inspecting the returned node sequence closely it seems that the string “Hello, x! Now you can ” is not a single text element, but a chain of text/atom/text. The Atom (the parent class of Text) corresponds to the inlined user name (“x”) and, I assume, indicates that the inlined characters may not be valid XML text, but instead PCDATA or Unparsed.

To make the specification pass, line 8 needed to be modified to:

8:          xhtml must ==/(<p>Hello, {"x"}! Now you can <a href="logoutURL">sign out</a> again.</p>)

Now that I have the behaviour-driven testing essentials under my belt, it’s all go to proceed on adding some features to my application.

Advertisements