London Geek Night

April 27, 2008

Thoughtworks office in London holds a Geek Night on 28/05/2008.

It’s open for everyone so don’t plan anything for the last Wednesday of May.

The topic concentrates around mocking. There will be jMock guys selling jMock and Felix talking about Mockito. Trust me, even if you know everything about mocking, this session will be interesting.

I’m not going to be there because in few days I’m moving to a different country :)


is there a difference between asking and telling?

April 26, 2008

These days testing interactions is getting very common. Mocking tools are becoming a necessary supplement to xUnit libraries precisely to facilitate testing interactions. I cannot imagine writing software without assert() (to test state) and verify() (to test interactions).

I’m about to show that it is very useful to distinguish two basic kinds of interactions: asking an object of data and telling an object to do something. Fair enough, it may sound obvious but most mocking frameworks treat all interactions equally and don’t take advantage of the distinction.

Let’s have a look at this piece of code:

Difference between asking and telling

Before mocking was invented we manually wrote stubs and tests looked like this:

Good old hand crafted stubs

Sometimes I miss those days before mocking. Test code looked so nice… The only problem was that hand writing every stub was quite cumbersome and produced tons of extra code.

Anyway, let’s try to extract a pattern from above test code:

1. when the repository is asked to find “foo” article, then return article
2.
deleteByHeadline(“foo”);
3.
make sure repository was told to delete article

So, to generalize it:

1. stub
2.
run
3.
assert

Now, let’s put it into words:

Interaction that is asking an object for data (or indirect input) is basically providing necessary input for processing. This kind of interaction is meant to be stubbed before running code under test (exercising the behaviour).

Interaction that is telling an object to do something (or indirect output) is basically the outcome of processing. This kind of interaction is meant to be asserted after running code under test.

Testing interactions like that is more natural and produces better code. Lessons learned from the old ways of testing interactions are implemented in Mockito:

Mockito distinguishes asking and telling

Controversies

Above approach may seem controversial (quoting interesting para):

Then, when you do verify(…), you have to basically repeat the exact same expression you put in stub(…). This might work if you only have a couple calls to verify, but for anything else, it will be a lot of repeated code, I’m afraid

Basically, the controversy is about repeating the same expression in stub() and verify():

Do I really need to repeate myself?

Do I really have to repeat the same expression? After all, stubbed interactions are verified implicitly. The execution flow of my own code does it completely for free. Aaron Jensen also noticed that:

If you’re verifying you don’t need to stub unless of course that method returns something that is critical to the flow of your test (or code), in which case you don’t really need to verify, because the flow would have verified.

Just to recap: there is no repeated code.

But what if an interesting interaction shares the characteristic of both asking and telling? Do I have to repeat interactions in stub() and verify()? Will I end up with duplicated code? Not really. In practice: If I stub then it is verified for free, so I don’t verify. If I verify then I don’t care about the return value, so I don’t stub. Either way, I don’t repeat myself. In theory though, I can imagine a rare case where I do verify a stubbed interaction, for example to make sure the stubbed interaction happened exactly n times. But this is a different aspect of behavior and apparently an interesting one. Therefore I want to be explicit and I am perfectly happy to sacrifice one extra line of code…

Finally…

Mockito recognises the difference between asking and telling, hence stubbing is separated from verification. Stubbing becomes a part of setup whereas verification a part of assertions. This produces cleaner code and gives more natural testing/TDD. It doesn’t increase code duplication as one might think. It’s just one of the ideas implemented in Mockito to make the mocking experience a little bit better. It’s not a silver bullet, though. Decent code is easily testable regardless of any mocking tools.


let’s spy

March 21, 2008

Following Gerard Meszaros: “Good names help us communicate the concepts”.

There is this Test Spy framework I worked on lately. Unfortunately, it doesn’t use ‘test spy’ metaphor at all. It talks about ‘mocks’ all the time. Some even say that the name of the library has something to do with mocking…

Was I just a foolish ignorant who didn’t want to acknowledge different kinds of mocks. Ouch! I should say: Test Doubles. In case you haven’t heard about Doubles: all those substitutes of real objects that make testing simpler or faster or more maintainable. I like them because they shrink the unit under test and make it easier to test.

I like simplicity. Introducing new concepts doesn’t make things simple. Do I really need Double, Dummy, Fake, Mock, Spy and Stub to write decent code? On the other hand, I definitely need them to communicate how to write decent code.

At the back of my weird mind I used to think that Test Double breakdown was a bit disconnected from the reality where subtle differences are blurred (and the existing tools/libraries didn’t really reduce the confusion). I tried to keep things plain but I reached the boundary: trying to keep things simple (and sticking to mocks and stubs) actually could have increased the confusion and made things complicated.

JamesBondThat’s why I’m about to sort out Mockito terminology. Better late than never, right?

In all of my previous posts ‘Mockito mock’ should be read ‘Test Spy’. But what’s the Test Spy anyway? Or better: what’s the difference between a Test Spy and a Mock? Both serve verifying interactions but the Spy is simple, lightweight and it gives very natural testing experience, close to good old assertions. Sounds interesting? Have a look at some of my previous rants or read this excellent post by Hamlet D’Arcy (don’t miss Collaborator Continuum).

Let’s get back to my favourite Test Spy Framework. Do you think following changes makes things simpler and easier to understand (I don’t really know the answer…):

@Mock -> @Spy

mock(Foo.class) -> createSpy(Foo.class)


Mockito @ Agile 2008

February 24, 2008

Just submitted session proposal for Agile 2008. It’s about Mockito (yes, I know I’m boring).

Competition is fierce and without proper (read: famous) name it will be difficult to get approved. But anyway: deadline for submissions is tomorrow. If you have any feedback about my session and you are willing to share it with me before end of tomorrow – I would be grateful.

I’m gonna present short version of this session during coming Last Thursday at Holborn office – see you there!


Can I test what I want, please?

February 24, 2008

Here’s the deal:

In state based testing (or return value testing) I assert that certain property has changed. I don’t care if other properties have changed – unless I explicitly write assertions for them. Great benefit of this style is the flexibility of testing: I can write small, targeted test methods. Basically, I can test what I want.

In interaction based testing I expect an interaction to happen. Even if I don’t care about other interactions I still have to expect them – to satisfy invasive mocks. This is how most mocking frameworks work and as a result, I cannot write small, targeted test methods. Basically, I cannot test what I want.

Some mocking frameworks are not invasive. Others offer tricks to reduce this problem – with various success rate and usually with side effects. Instead of jumping into examples let me ask you:

Does your mocking framework let you test what you want?

Expecting a single interaction in most mocking frameworks means: 1. this interaction must happen. 2. other interactions must NOT happen. Do you imagine if an innocent assertion of the state worked like that? Asserting one property meaning also asserting that NONE of the other properties have changed?

defensiveLet me rephrase my initial question: Why testing interactions has to be more defensive than testing state?

Is it because we fell in love with pre-programmed, intelligent mocks? Is it because of the way mocking frameworks are implemented? Or perhaps because of the strive to have a decent point of failure – mock can bark with unexpected interaction straight in the code so it’s very easy to find it?

I’m not buying it. When it comes to behaviour verification, Mockito provides excellent point of failure. Also, Mockito can detect any kind of unexpected interactions. Oh, and Mockito lets me test what I want…

Mockito mocks are tamed. They don’t make decisions for me. They don’t know which interactions are expected or unexpected. I rule my mocks. I rule my code. And it pays back generously: code is cleaner and reacts better to changes.

By now, you’ve probably figured out that Mockito is not strictly a mocking framework. It’s rather a spying/stubbing framework but that’s a story for a different post.


expect-run-verify… Goodbye!

February 1, 2008

Expect-run-verify is the most common pattern in mock frameworks. (update: I called it record-replay-verify before – my bad – expect-run-verify is what I really meant).

What’s wrong with it?

  1. Codebase suffers. Test methods become noisy. I have to expect/record some interactions not because I want to test them but because mocks complain if I don’t do it.
  2. Doesn’t give me a natural test-drive. I prefer when expectations become assertions and appear after execution – it’s very intuitive.
  3. Tests are fragile. Test driving new functionality that requires additional interaction often breaks all tests. Thanks to the aggressive nature of expect-run-verify.
  4. Could give better failures. When expectation becomes assertion, failure shows exact line of code. No more deciphering exception messages – just click on first element on stack trace.
  5. Could read better. Separation of stubbing and expectations reads really nicely.

Today I discovered MoQ – little mocking library for .NET. When I read how MoQ was invented I see many similarities with my own thinking process that pushed me to write Mockito.

MoQ uses C# 3.0 sugar like lambda expressions. Mockito is a java creature. Both don’t like record/playback model. Mockito goes even further and abandons expect-run-verify.

dirtyharry

Expect-run-verify…

Goodbye!

Let me enjoy most natural test-drive: as close to state based testing as possible. Expectations in Mockito are like assertions – good old friends of state based testing.

Java TDDer have several options these days:

  1. Using hand crafted stubs/mocks: too much boilerplate, too many lines of code, chaos of stubs.
  2. Using existing mock libraries: less some obscure exceptions it’s all expect-run-verify stuff.
  3. Mockito: just try it and tell me what you don’t like about it :)

I know that many test-infected java people on this planet don’t use mock frameworks. They code mocks/stubs from scratch because they find mock libraries too annoying. Mockito offers simplicity and flexibility of hand crafted mocks and yet eliminates so much boilerplate code. I encourage you to try it out.


10 rules of (unit) testing

January 31, 2008

There you go, those are my 10 rules of (unit) testing. It’s nothing exciting, really. Everyone is so agile these days. Are you agile? I bet you’d say: I was born agile.

10c

Here I come with my own 10 commandments. I came up with those while doing research on mock frameworks (haven’t you heard about Mockito, yet? it’s the ultimate tdd climax with java mocks). I browsed so much of our project’s test code that I feel violated now (codebase is nice, though).

  1. If a class is difficult to test, refactor the class. Precisely, split the class if it’s too big or if has too many dependencies.
  2. It’s not only about test code but I need to say that anyway: Best improvements are those that remove code. Be budget-driven. Improve by removing. The only thing better than simple code is no code.
  3. Having 100% line/branch/statement/whatever coverage is not an excuse to write dodgy, duplicated application code.
  4. Again, not only about test code: Enjoy, praise and present decent test code to others. Discuss, refactor and show dodgy test code to others.
  5. Never forget that test code is production code. Test code also loves refactoring.
  6. Hierarchies are difficult to test. Avoid hierarchies to keep things simple and testable. Reuse-by-composition over reuse-by-inheritance.
  7. One assert per test method is a bit fanatical. However, be reasonable and keep test methods small and focused around behavior.
  8. Regardless of what mock framework you use, don’t be afraid of creating hand crafted stubs/mocks. Sometimes it’s just simpler and the output test code is clearer.
  9. If you have to test private method – you’ve just promoted her to be public method, potentially on different object.
  10. Budget your tests not only in terms of lines of code but also in terms of execution time. Know how long your test run. Keep it fast.

Number #1 is my personal pet. Everybody is so test-driven but so little really care about #1 in practice. Best classes, frameworks or systems offer painless testing because they’re designed & refactored to be testable. Let the code serve the test and you will produce delightful system.

Number #7 is a funny one (‘Cos we need a little controversy). The whole world rolls in the opposite direction. Maybe I just don’t get it… yet. Or maybe it’s because I paired with young one-assert-per-test guy once. He cunningly kept writing test methods to check if constructor returns not-null value. If I had to play this game and chose my one-something-per-test philosophy I’d steal MarkB’s idea: one-behaviour-per-test. After all, It’s all about behavior…


Mockito

January 14, 2008

I’m a mockist but existing mock frameworks just don’t appeal to me. They spoil my TDD experience. They harm code readability. I needed something better. That’s why I came up with Mockito.

Syntax

Here is a what I think about mocking syntax:

  • Let’s keep it simple: interactions are method calls. There is no point in building sophisticated mocking language for method calls in Java. There is already a language for that. It’s called Java.
  • The less DSL the better. Interactions are just method calls. Method calls are simple, DSL is complex.
  • No Strings for methods. I spent more time reading code than writing it. Therefore I want the code to be readable. String literals pretending to be methods cannot compete with actual method calls. Even IDEs decorate literals differently so my mind will always adopt the real method call quicker than any literal trying to impersonate a method.
  • No anonymous inner classes. They bring more indentation, more curly brackets, more code, more noise. Did I mention that I spent more time reading code?
  • Painless refactoring. Renaming a method should not break my tests.

That’s why I really like the syntax of EasyMock.

Long journey from EasyMock to Mockito

I was brought up on EasyMock. Normal kids got milk I got classes to test. Over the years on different projects I saw idyllic world of hand crafted stubs being overthrown by EasyMocks. On other project, jmock was doing fine until he got a Chuck’s roundhouse kick to the face by EasyMock. Finally, I saw resentment to EasyMock and triumphatic comeback of hand crafted stubs… Sometimes the resentment to EasyMock was a bit naive (“My class has 10 dependencies and is difficult to test. Therefore EasyMock sucks”). Sometimes it was clearly righteous…

Here is what I wanted to achieve with Mockito so that it suits me better in test-driving code the way I like:

tdd

Focused testing. Should let me focus test methods on specific behavior/interaction. Should minimize distractions like expecting/recording irrelevant interactions.

Separation of stubbing and verification. Should let me code in line with intuition: stub before execution, selectively verify interactions afterwards. I don’t want any verification-related code before execution.

Explicit language. Verification and stubbing code should be easy to discern, should distinguish from ordinary method calls / from any supporting code / assertions.

Simple stubbing model. Should bring the simplicity of good old hand crafted stubs without the burden of actually implementing a class. Rather than verifying stubs I want to focus on testing if stubbed value is used correctly.

Only one type of mock, one way of creating mocks. So that it’s easy to share setup.

No framework-supporting code. No record(), replay() methods, no alien control/context objects. These don’t bring any value to the game.

Slim API. So that anyone can use it efficiently and produce clean code. API should push back if someone is trying to do something too smart: if the class is difficult to test – refactor the class.

Explicit errors. Verification errors should always point stack trace to failed interaction. I want to click on first stack element and navigate to failed interaction.

Clean stack trace. Part of TDDing is reading stack traces. It’s Red-Green-Refactor after all – I’ve got stack trace when it’s red. Stack trace should always be clean and hide irrelevant internals of a library. Although modern IDE can help here, I’d rather not depend on IDE neither on competence in using IDE…

road split

EasyMock is a decent piece of software, credits go to kick-ass people who wrote it. Initial hacks on Mockito were done on top of the EasyMock code but since then I rewrote most of the codebase. Enjoy.


Follow

Get every new post delivered to your Inbox.