Mocking v2.0

We all love to use mocks in our Java tests, right? Add the usual mock framework to your test dependencies, sprinkle a few mock, when and thenWhatever calls in to your code, and happy days. You’re able to test things in isolation, and as an added bonus ensure your code is actually calling the stuff it’s supposed to be calling by verifying the mock afterwards. The sun is shining, life is good, and your code is tested to perfection.

But then the clouds roll in, and you have to test a final class. Or you need to mock out a static method in some legacy code. Or, horror, some code that directly calls new on a class you want to mock.

You could hit up StackOverflow, where you’ll find that all these things are possible with existing frameworks, assuming you’re prepared to add in another dependency, use a ton of boilerplate, and refactor your code a bit. Depending on which framework you’re currently using there are a ton of different ways you can kind of achieve what you need.

By now you’ve sunk another hour or two, and it’s still not quite working.

What if there was another way?

The other way

What if I told you there was a framework out there that let you take a final class, and just do this?

mockClasses(FinalClass.class);

FinalClass sc = new FinalClass();

assertThat(sc.returnHello()).isNull();

assertMock(() -> sc.returnHello()).wasCalledOnce();

when(() -> sc.returnHello()).thenReturn("Goodbye");

assertThat(sc.returnHello()).isEqualTo("Goodbye");

assertMock(() -> sc.returnHello()).wasCalledTwice();

What if it also did statics, with the same API, and no extra dependencies?

mockClasses(ClassWithStatic.class);

assertThat(ClassWithStatic.returnHello()).isNull();

when(() -> ClassWithStatic.returnHello()).thenReturn("Goodbye");

assertThat(ClassWithStatic.returnHello()).isEqualTo("Goodbye");

What if it even let you mock out constructors?

final RuntimeException rte = new RuntimeException("MARKER");

mockClasses(FinalClass.class);

when(() -> new FinalClass()).thenThrow(rte);

assertThatThrownBy(() -> new FinalClass()).isSameAs(rte);

What if we put all our arguments about whether we should be doing this kind of mocking to one side for now, because sometimes in life, you’re faced with a nail.

And when you’re faced with a nail, you need a hammer.

There’s one here: https://github.com/roscopeco/moxy

Or grab it with Maven:

<dependency>
	<groupId>com.roscopeco.moxy</groupId>
	<artifactId>moxy-core</artifactId>
	<version>0.90.1</version>
</dependency>
Advertisements

ORMDroid 0.20 now available

ORMDroid 0.20, the first packaged release of the ORM framework for android, is now available from the project downloads page on Google Code. This first release packages up the Android library ADT project, adds some documentation (which you can view online here), and makes it easy to grab and go if you don’t like to/want to work with the Subversion repository.

In case you missed it, you can read more about ORMDroid here, here and here.

Spritesheets with Gimp – An adventure in Scheme

One of the coolest Android projects I’m involved with at the moment is a new strategy game, and one of the coolest things about it is it’s retro-look 8-bit style graphics. Growing up in the 80’s I obviously got a lot of exposure to the unique look of games in the 8-bit era, and I have fond memories of hacking away on the C64 and Spectrum, trying to represent real objects in a tiny number of pixels. So I’m really loving the resurgence of these techniques on current mobile devices.

Although there are a few “pixel art” graphics tools out there, we’re actually using the gimp to create our art (it’s what we know and love) and the game itself is using a layered sprite system to allow us to keep raw data to a minimum and also to make it easy for us to use different permutations of layers to create different sprites. For example, all the characters in the game are built from a small set of sprite layers which we just overlay in different combinations.

Perhaps an example is in order. Consider the rather snazzy (and somewhat surprised) looking individual on the left. He’s actually composed of a number of different layers in gimp, which are grouped and arranged in such an order that when one layer from each group is visible, they combine to create a character (in this case a mildly-shocked purple-haired gentleman in a blue sweater).

There are a number of these files, some covering people (as in this example), some with vehicles, some with background objects, and so on. And in each one, there are many layers each with a different sprite image. Not all are overlaid in this way, but they all use gimp’s layer features. Continuing the example, the image on the right shows you the gimp layers palette with the various layers that comprise the purple-haired dude.

If you look carefully you’ll see that our chap comprises a number of layers, with helpful names such as “skin_med” and “hair_02_purple”. All this works great while we’re actually drawing stuff, but once we come to actually put it into the game, we’re obviously not importing layered XCF  files – instead we break up the layers into a sprite sheet which flattens all the layers out and arranges them side-by-side in a single image (traditional sprite-sheets actually use multiple rows and columns, usually to give a fixed width and height as required by the hardware – we’re not doing this at the moment, although we do support it in the graphics engine). Turns out that this is not especially well supported in gimp.

Originally, we were using the built-in filmstrip plugin to accomplish this, but this was always a stop-gap solution – filmstrip is designed for use with photos, as a visual effect. As such, it actually adds virtual sprocket holes, frame numbers, and other assorted things. All nice if you’re making a montage of your week in Barbados, but no so great if you’re trying to get an exact-sized image you can then index into by pixel from your code. It is possible to stop these effects by tweaking the settings, but they don’t get saved across sessions, and in any event it doesn’t support transparent backgrounds so there’s always an extra select by colour/delete step once the sheet is made.

Luckily, Gimp supports scripting (via it’s Script-Fu interface to the Scheme language), so it was a fairly simple matter to knock up a script to take care of the conversion from layered image to flattened spritesheet. Gimp also supports Python scripts, but given the choice between a whitespace-sensitive language and a Lisp-like dialect, I’ll take the latter every time. It’s been a while since I last wrote Scheme, making it an ideal time to brush up some skills. A definite win-win situation!

After a little hacking around the API (Script-Fu has changed a bit since I last used it, but not so much that it’s unrecognisable) I had a basic working script, which I could call at any time through a menu item (on a new ‘Sprite’ menu I added, in anticipation of further scripts and plug-ins the guys have already asked me for). Going back to our example, the script creates a spritesheet in a new image, which for the guy above looks like:

Obviously, this example is so contrived as to be pointless. The real files have many more sprite tiles than this – I don’t think I’d be too popular if I started dumping all our graphic artifacts on here – but you get the idea.

And just in case you’re doing something similar and might find this useful, here’s the code. Call it a Saturday present from me, to you.

; Script to convert image layers to a sprite sheet.
; Copyright (c) 2012 Ross Bamford.
; http://www.apache.org/licenses/LICENSE-2.0.html
(define (script-fu-spritesheet img)
  (let* (
      (layer-count (car  (gimp-image-get-layers img)))
      (layer-ids   (cadr (gimp-image-get-layers img)))
      (sprite-width(car  (gimp-image-width img)))
      (spritesheet-width (* sprite-width layer-count))

      ; Create new image with appropriate size
      (spritesheet-image (car (gimp-image-new 
                                      spritesheet-width
                                      (car (gimp-image-height img)) 
                                      RGB)
                          )
      )
    )

    ; Copy and move each source layer appropriately
    (let (
        (i (- layer-count 1))
      )

      (while (> i -1)
        (let (
            (new-layer (car(gimp-layer-new-from-drawable 
                                      (aref layer-ids i) 
                                      spritesheet-image)
                        )
            )                     
          )

          (gimp-image-insert-layer spritesheet-image new-layer 0 -1)        
          (gimp-layer-translate new-layer (- spritesheet-width (* sprite-width (+ i 1))) 0)
          (gimp-item-set-visible new-layer TRUE)
        )

        (set! i (- i 1))
      )
    )

    ; Merge layers and rename
    (gimp-image-merge-visible-layers spritesheet-image CLIP-TO-IMAGE)
    (gimp-item-set-name (aref (cadr (gimp-image-get-layers spritesheet-image)) 0) "spritesheet")

    ; Create view for new image
    (gimp-display-new spritesheet-image)
  )
)

(script-fu-register "script-fu-spritesheet"
                    "Create spritesheet"
                    "Create a spritesheet from current image layers"
                    "Ross Bamford"
                    "Copyright (c)2012 Ross Bamford"
                    "2012"
                    "*"
                    SF-IMAGE    "Image"         0)
(script-fu-menu-register "script-fu-spritesheet"
                         "<Image>/Sprites")

(Caveat: I’m not primarily a scheme programmer. If you are, and you find my style abhorrent, well, tough :D)

(Postscript: Turns out that WordPress.com doesn’t support Scheme in it’s sourcecode tags! Thanks to the guys over at tohtml.com for their highlighter, even though I had to pretend this was lisp to get it highlighted anything like properly.)

ORMDroid on Google Code

Further to my previous post, I spent a bit of time today getting the ORMDroid project set up on Google Code (Edit: Moved to Github), including adding a bit of sample code to get you going with the library. I’m also working on extracting a simple sample project that will also go in the repository, which will serve as a proof of concept, a working example, and a functional testbed all in one.

Getting up and running with ORMDroid is really simple. Firstly, you need to add a single XML tag to your AndroidManifest.xml (it should be a child of the Application tag):

<meta-data
    android:name="ormdroid.database.name"
    android:value="your_database_name" />

Next, you need to initialize the framework somewhere. Application.onCreate() is the logical choice if you’re using a custom Application class (configured in your manifest – see Google’s JavaDocs if you want to go this route), but  you can happily call this from pretty much anywhere – even your activity’s onCreate() – since there’s actually no penalty for calling the initialize method multiple times.

ORMDroidApplication.initialize(someContext);

Side note: Currently, ORMDroidApplication is itself a subclass of android.app.Application, so you could go down the route of setting it directly as your application class, or subclassing it with your custom behaviour, and have the initialization handled transparently for you. However, this isn’t the recommended way, and it’s possible this facility will be removed in future versions.

With the framework initialized, you can start loading and saving your models! These are just plain Java POJOs that subclass the ORMDroid Entity class. If you’re happy with the default table and column names provided by the framework, these can be as simple as:

package com.example.myapp;

import com.roscopeco.ormdroid.Entity;

public class Person extends Entity {
  public int id;
  public String name;
  public String telephone;
}

Working with the Person class is now as simple as:

Person p = Entity.query(Person.class).where("id").eq("1").execute();
p.telephone = "555-1234";  // for example...
p.save();

And that’s it. No, really, it’s that simple. You don’t have to worry about setting up the database, ensuring tables are created, transaction management, or any of that other stuff. Of course, you can handle the database yourself if you really want to, but ORMDroid is more than happy to take care of it for you if you’ll let it.

The entity class in the example above will be stored in the following table:

CREATE TABLE comexamplemyappPerson (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, phone VARCHAR);

If you aren’t happy with this default mapping, you can use the Table and Column annotations to customize things, e.g:

package com.example.myapp;

import com.roscopeco.ormdroid.Entity;
import com.roscopeco.ormdroid.Table;
import com.roscopeco.ormdroid.Column;

@Table(name="people")
public class Person extends Entity {
  @Column(name="person_id", primaryKey=true)
  public int id;

  @Column(name="fullname")
  public String name;

  public String telephone;
}

A couple of things to note here are that the primaryKey parameter is actually redundant, since id would be used as a primary key in the absence of another field that has primaryKey=true, and that, and that you don’t have to annotate all the columns – only those you want to change the default mapping for.

And that’s it. You’re up and running with ORMDroid! Obviously this example code is very simple, and misses out probably the most important point with using an ORM framework – relationships. You can play with this yourself though – create another entity class, and give it a Person field. By default, whenever you persist your new class the related Person will be persisted as well. One-to-one relationships are already supported, and it’s easy to add helper methods to support many relationships using the query facilities provided by Entity. We’ll take a detailed look at relationships at a later date (this post is already long enough), but for now take a look at the code and I guarantee you’ll pick it up in no time anyway.