Showing posts with label testing. Show all posts
Showing posts with label testing. Show all posts

Thursday, November 11, 2010

Deep thoughts about deep mocks

A deep mock is a mock that has methods that also return mocks. In theory, you could follow a chain of mocks for as long as you wanted.

Deep mocks are supported by both Mockachino and Mockito, with the exception that a method from a mock can't return a mock if the return type is primitive or final.

Another problem with deep mocks was previously generics.
The following would fail in both Mockachino and Mockito:
static interface ListSet extends List<Set> {}
@Test
public void testDeepMockWithClass() {
ListSet mock = mock(ListSet.class, RETURNS_DEEP_STUBS);
Set mock2 = mock.get(0);
}

This would fail on the last line, because the mocking frameworks wouldn't understand that the return type of get(int) should be Set instead of Object.

This has been fixed in Mockachino 0.5.0 (with a fairly small patch, I'm happy to say!) but it is still broken in Mockito 1.8.5.

Now, this particular example takes advantage of the fact that the class we're dealing with has no open generic types. The type is fully bound.

It would be much harder to support something like this:
@Test
public void testDeepMockWithClass() {
List<Set> mock = mock(List<Set>.class, RETURNS_DEEP_STUBS);
Set mock2 = mock.get(0);
}


This is in fact not even legal Java syntax. It's also not valid Java semantics, since the runtime doesn't maintain type information except for some special cases.
So we simplify it into this, which is valid Java syntax:
@Test
public void testDeepMockWithClass() {
List<Set> mock = mock(List.class, RETURNS_DEEP_STUBS);
Set mock2 = mock.get(0);
}

Unfortunately, at the time of the call to mock, we only know about List.class, not that it should have Set as its generic type parameter, so it would be impossible to deduce which type it should create at mock.get(0).

This has two possible solutions. Either create a specific sub interface/class, like we did with ListSet. The other solution is to use the TypeLiteral concept, found in Google Guice:
@Test
public void testDeepMockWithClass() {
List<Set> mock = mock(
new TypeLiteral<List<Set>>() {},
fallback(DEEP_MOCK));
Set mock2 = mock.get(0);
}


Since we're actually creating a new anonymous class here, Java manages to retain the type information. It's unfortunately a bit verbose, but it should still come in handy in the few times you'd need to use deep mocks with generics.

Sunday, June 6, 2010

Automated tests for content

Games are generally considered to consist of code and content.
  • The code is the game engine that defines all the rules of the game, input handling, network, graphics rendering, and so on.
  • Content in a game includes a lot of things: textures, sounds, level designs, ai, animations, meshes, dialogues and more.
Another (less formal) way of looking at it is that code is the part of the game produced by the programmers, and content is the part of the game produced by artists, game designers or level designers.

Programmers are used to writing tests for their code (if they're using TDD, they're even writing some, if not all, tests before they write the code), but content creators generally are not. They instead rely on manual testing, both by themselves and by gameplay testers.

Why is code tested and not content?
I think the code is what makes the game robust, coherent and logical. It's easy to detect broken code - broken code either crashes or behaves incorrectly. This makes it feasable to write tests for the code.

Content on the other hand is harder to verify automatically. How can a machine decide that a texture is broken? We could certainly verify that the texture has the correct dimensions and correct color depth, and other properties needed for the game engine to support it. We should have tests to verify the integrity of the content to as large extent as possible, and I think we do.

The things we can't verify automatically is the fun and the user experience.

The corner case
This was just the setup. Now for one of the corner cases, the parts that can be considered both code and content: AI!

AI is definitely a part of the content. Meeting unique non-player characters (NPC) with custom AI adds a new user experience that is something unknown, and therefore possibly exciting. The AI however is also expressed in some sort of code, either as a script in some embedded language, as a behaviour tree or behaviour stack.

The problem with AI as code, is that it tends to mutate at a much faster pace than game engine code. AI is driven by the content around it, not technical demands, and so it must change often.

Writing tests for each individual AI is expensive, since fully testing all the possible code paths can require a lot of manual setup, and verifying correctness is also tricky for a suffiently complex AI. What's worse, the test is bound to be very fragile, since content makers like to tweak and redo AIs if it's too easy, too difficult or simply not fun enough.

Should content like this be covered by automated tests? To some extent, definitely! I am not convinced that content should be tested individually, but testing the content by type is quite useful to detect errors.

For AIs this could mean:
  • Running automated smoke tests that run the AI characters for a long time (game time, not real time) to increase the chance of running many code paths (possibly with the AI opponent doing random moves) and simply checking that it doesn't crash. This type of test could apply to most if not all AI. It would be cheap to implement, and probably be fairly stable.
  • Smoke testing the AI with measurements of key values, such as damage output, movement speed, actions per minute, et.c. and check that the values are in a sane range. If some of the values are zero, this would indicate that the AI is blocked somewhere and one of the code paths is never run, and extremely high values would indicate that the AI is stuck in one of the code path loops.
Conclusion
You should always consider the cost versus the gain of writing tests. For game engine code, the gain is almost always greater than the cost, but for content it's not as clear.
You should also consider how to test something. A small unit test is suitable for many parts of code development, but it's probably overkill for content (which tends to change a lot).
If you can write one or a few tests that can verify something about a specific content type, and apply the test to all the content, the gain will quickly become large, since you can scale up the size of the content without scaling up the number of tests.

Tuesday, May 25, 2010

Temporal testable code

A lot of code is time dependent. Code either needs to wait or timeout for a specific amount of time, or it needs to fetch the current system time for some reason.

If the code uses Thread.sleep(), System.currentTimeMillis(), new Date(), or anything like that, it has a hidden and implicit dependency. This can be a problem when you're trying to write tests for such code.

The tests usually end up with a lot of:

Thread.sleep(1000); // wait for code to finish doing its job.

This will make your test suite unnecessarily slow to run, and you want your tests to finish almost instantly.

The solution is to convert this implicit dependency to an explicit!
This is done by creating the following interface:

public interface TimeProvider {
long now(); // Replaces System.currentTimeMillis();
sleep(long timeInMilliSeconds) throws InterruptedException; // Replaces Thread.sleep
}


All the code that is time dependent in any way should inject an object of this interface.
Now, you need two implementations of this interface, one for real usage and one for testing. Fortunately, these are trivial to write:


public class SystemTimeProvider implements TimeProvider {
@Override
public long now() {
return System.currentTimeMillis();
}

@Override
public void sleep(long timeInMilliSeconds) throws InterruptedException {
Thread.sleep(timeInMilliSeconds);
}
}

public class MockTimeProvider implements TimeProvider {

private long now;

public void setNow(long now) {
this.now = now;
}

public void advanceTime(long amountInMillis) {
now += amountInMillis;
}

@Override
public long now() {
return now;
}

@Override
public void sleep(long timeInMilliSeconds) {
now += timeInMilliSeconds;
}
}


For the real application, everything will behave the same.
For testing purposes, just inject the MockTimeProvider instead, and manually manipulate the time.

Here's simple example to illustrate how this works in practice.
Basically we want to ensure that when we generate UUIDs, a specific part of the UUID remains the same if two UUIDs are generated close enough temporally, but different if there's a small time difference:


public class UUIDTest {
private final MockTimeProvider mockTimeProvider = new MockTimeProvider();
private final UUIDFactory factory = new UUIDFactoryImpl(mockTimeProvider, new SecureRandom());

@Test
public void combTest() throws InterruptedException {

mockTimeProvider.setNow(0);
UUID firstUuid = factory.combUUID();
UUID secondUuid = factory.combUUID();

assertFalse(firstUuid.equals(secondUuid));
long combPart1 = getCombPart(firstUuid);
long combPart2 = getCombPart(secondUuid);
assertEquals(combPart1, combPart2);

mockTimeProvider.advanceTime(20);

UUID thirdUuid = factory.combUUID();
long combPart3 = getCombPart(thirdUuid);
assertFalse(combPart1 == combPart3);

}

private long getCombPart(UUID uuid) {
String combString = "0x" + uuid.toString().substring(24, 36);
return Long.decode(combString);
}
}
Stop using static ways of using time in your code!
Using an injected TimeProvider works almost identically if it's a SystemTimeProvider, so the only cost is a slightly more costly method invocation since it's through an additional abstraction layer.
But the benefits are huge! Your code will be more testable, and the dependency on time is no longer hidden.

Monday, May 17, 2010

TDD - levels of insight

Test Driven Development (or Design) is a method of developing code where you first write small tests that express the requirements, it can either be requirements from the customer or product owner, or requirements the developers themselves deduce are needed of the product.

The idea is that by writing the tests first, the design of the code improves, because it will automatically become modular (writing tests for code that's not modular is much harder, if not impossible). The tests also increase your development speed, since running your suite of tests takes a much shorter time than starting up the application and manually testing everything. If you make a mistake somewhere when refactoring the code or writing a new feature, it will become obvious directly, since the tests will expose it, if it breaks any of the requirements.

But let's not go into the details of TDD, there are plenty of other sources that describe TDD much better than I ever could.

Instead, this blog post will be about a hypothesis I have.
I don't believe you can really study TDD and just get it. You have to try it out for yourself and become convinced by experiencing the benefits. You will notice that you can keep maintaining a project without losing speed and your code will be extendable.

So what is the hypothesis? Glad you asked!
Every developer will go through a series of levels of insight, with each level being closer to being a TDD master.

And here are the levels I've identified, based on anecdotal evidence consisting of my personal experience, and what I've observed in others.

#1 Obliviousness
As a fresh developer, it's obvious that at some point in your life, you didn't know about TDD. I'd also take a guess that it's common to start programming before starting to write tests. From the various educations I've been to and talked to others about, testing is not something that's introduced early in programming training.

Obliviousness simply means that you're unaware of TDD is a practice and its usefulness. I was unfortunately in this category for much too long, which I suspect is true for a lot of developers.

#2 Disregard
The next step is hearing about TDD and getting the initial thought: "Writing tests first? That sounds backwards!". Not only that, you may also think that is seems like a waste of time to spend a lot of time writing tests that will soon be obsolete anyway, or tests for things that have obvious failures "I'll obviously notice immediately when starting up if this breaks".

#3 Awareness
Level 3 is being aware of TDD and that it can be a useful tool, and not just a stupid overhead designed as support for bad developers.

The easiest way to get past level 2 onto level 3 is to work with someone who's already past it, who seems to be using it successfully.

"Hmm, that guy produces clean code and doesn't seem to introduce as many bugs as I do, I wonder why..." Deeper investigation may lead to the introduction of TDD.

This may inspire you to try out writing tests first (or just writing tests at all), but since you're unfamiliar with TDD to begin with, your code will be hard to test, and it will be a pain to write the tests. You'll spend a long time to write the test, and you'll become irritated. "Do I really gain anything from spending so much time writing tests instead of producing code? QA will find any bugs I produce anyway, better to spend the time later to bugfix it instead."

Unfortunately, this is a typical setback that some people fail to get past.

#4 Empirical
Level 4 is when you've tried TDD for such a long time that you're really convinced that it's the best way to develop.
To reach this level, you need to really have used for such a long time that you have started to reap the benefits.

You have may have done a simple refactoring or introduced a new feature when one of your oldest tests break, and you look into it. "Aha, of course I needed to consider that before I did this, no wonder it broke!".

This is when you'll start building up the confidence in your code. If you introduce some code change that will break something, your tests will catch it.

Writing good tests, and writing them before the code is hard, as is writing clean and modular code. Becoming good at TDD takes time and effort, but it also makes you a better developer and better designer. Suddenly all your code will have at least two use cases - the test code and the runtime code.

#5 Mastery
After having been in level 4 long enough, TDD will become second nature to you.
You would use TDD for all development with the insight that it drives good design and saves time. No aspect of code is too hard to write test driven for a master, not even the typical daunting tasks intimidates the TDD master: UI, database, network, et.c.

Conclusion
I personally am stuck in level 4 at the moment. Perhaps I'll stay there forever, but even so it's probably a good idea to keep striving to reach level 5. I do this by trying to embrace TDD in my development as much as I can, but how can I be sure that's enough? Perhaps some other insight is needed to step up to the next level.

If I find any answers to that, You can expect a follow up post.

Sunday, February 21, 2010

Mockito vs Mockachino

I wrote down some differences between Mockito and Mockachino, ordered by how important they are for actual mock usage.

Note that I am quite biased since I actually wrote Mockachino, but I'm also a great fan of Mockito and I still prefer Mockito over all other java mocking frameworks. I have tried to be as objective as possible, but if I have missed some important aspect to compare, please let me know, and I'll add it.

The basic syntax
The syntax is definitely one of the most important aspect of mocking, especially when comparing frameworks that are similar in most other regards.
Mockito and Mockachino have slight differences in syntax, with the biggest difference being when stubbing a mock method:

// Mockito
when(mock.theMethod(eq(value1), eq(value2), same(value3))
.thenReturn(theReturnValue);
// Mockachino
stubReturn(theReturnValue).on(mock).theMetod(value1, value2, same(value3));

Mockito has a better flow here: you first type what you want to match on and then what you want to return. Mockito also has a type safe return value, since the compiler will enforce that theReturnValue is of the same type as the return type of mock.theMethod().

There are a couple of disadvantages of this approach:
  1. It actually needs to invoke the mock first, and then undo the side effect it produces. This is actually impossible to do if the mock is actually a spy. What Mockito actually does here is remove the invocation from the mocks call history so it won't be a false match in any later verification.
  2. The mock invocation might actually throw an exception, which will kill the test. The workaround for this is to use Mockitos alternative syntax, which is more similar to Mockachinos. More in this problem later.
  3. It's not possible to use mocks inlined here, since that will confuse the stubbing mechanism, which basically just remembers the latest invoked mock when adding the stubbing.
Mockachino's approach may seem a bit backwards at first but it's generally not much more difficult to grasp than the difference between these sentences:
  1. When you call my by the phone number 08-123 456, I will send a fax reply back.
  2. I will send a fax reply back when you call me by the phone number 08-123 456.
Mockachino is a bit more consistent in its syntax here. Every kind of interaction with the mock (stubbing, adding observers, verifying behaviour) has the same syntax:

// Stubbing
stubReturn(theReturnValue)
.on(mock).theMetod(value1, value2, same(value3));
// Observing
observeWith(observer)
.on(mock).theMetod(value1, value2, same(value3));
// Verifying
verifyOnce()
.on(mock).theMetod(value1, value2, same(value3));
As you can see, they all end with
on(mock).theMetod(value1, value2, same(value3));
which is quite consistent. It also keeps the mock object close to the method call.
Compare it with Mockito, which breaks up this pattern by having additional parameters between the mock and the method call when verifying:
verify(mock, times(1)).theMetod(value1, value2, same(value3));

Clean stacktrace
Both Mockito and Mockachino clean up stacktraces upon errors, which means that the stacktrace will exclude all Mockito/Mockachino stack elements

Mixing argument matchers and plain arguments
When stubbing or verifying a method in Mockito, you may choose to use argument matchers instead of values, which gives you great flexibility. However, you can not mix them. The solution is simple: just add the eq()-matchers for everything that you don't want to match explicitly.

Mockachino has a slightly more friendly approach. It allows mixing plain values with matchers, as long as the plain values are not the default values for their type (i.e. null, false, 0, '\0').

In order verification
Mockito has a couple of bugs (or design choices) when trying to verify things in order. Here is one:

@Test
public void testInOrder() {
List mock = Mockito.mock(List.class);
mock.add("Foo");
mock.add("Bar");
mock.add("Foo");

InOrder order = Mockito.inOrder(mock);
order.verify(mock, Mockito.atLeast(1)).add("Foo");
order.verify(mock, Mockito.atLeast(1)).add("Bar");
order.verify(mock, Mockito.atLeast(1)).add("Foo");
}

This fails, even though it's clear that it shouldn't.
Compare with the Mockachino example below. This works as expected.

@Test
public void testMockachinoInOrder() {
List mock = Mockachino.mock(List.class);
mock.add("Foo");
mock.add("Bar");
mock.add("Foo");

InOrder order = Mockachino.verifyOrder();
order.verifyAtLeast(1).on(mock).add("Foo");
order.verifyAtLeast(1).on(mock).add("Bar");
order.verifyAtLeast(1).on(mock).add("Foo");
}
Singleton ordering per mock object
In Mockito, one mock object can only have one ordering-object. This means that the following does not work:

@Test
public void testMockito() {
List mock = Mockito.mock(List.class);

mock.add("Foo");

InOrder order1 = Mockito.inOrder(mock);
order1.verify(mock).add("Foo");

InOrder order2 = Mockito.inOrder(mock);
order2.verify(mock).add("Foo");
}

In Mockachino, each ordering object is different and holds its own verification state. This works as expected:

@Test
public void testMockachino() {
List mock = Mockachino.mock(List.class);

mock.add("Foo");

OrderingContext order1 = Mockachino.newOrdering();
order1.verify().on(mock).add("Foo");

OrderingContext order2 = Mockachino.newOrdering();
order2.verify().on(mock).add("Foo");
}

Multithreading
Mockito fails with incorrect error messages when trying to use the same mock in multiple threads.
With Mockachino, multithreading is not a problem. You can share mock contexts and even mocks between threads

equals, hashCode and toString
These three methods can be tricky, since they are base methods used a lot by Java standard libraries (Sets, Maps, Lists, et.c.). Mockachino supports stubbing of all these methods, Mockito only supports stubbing toString. Stubbing these methods can be very useful at times, such as using mocks as keys in maps where a correct equals and hashCode are essential.

When it comes to verifying, all these are possible to verify with Mockachino, but it's not always a good idea, since these methods can be called almost anywhere. Also, the correctness of your code should probably not depend on specific calls to these methods.

API that never lies

Mockito uses a generic VerificationMode parameter to the verify methods, but all verification modes do not work for InOrder verification. This is very unclear in the API.
Mockachino instead hides its unsupported modes in the ordering API.

Support for inline mocking
Since Mockito does a lot of dark magic to enable its terse syntax, it's quite frail when you interrupt its expected flow of constructs. Inline mocking is a perfect example of this.
I have on several occasions had the need to let a mock return another mock.

This, and similar constructs fails in Mockito:

@Test
public void testInlineMockito() {
List mock = Mockito.mock(List.class);
Mockito.when(mock.get(0)).thenReturn(Mockito.mock(List.class));
}

The workaround is at least simple:

@Test
public void testInlineMockitoWorkaround() {
List mock = Mockito.mock(List.class);
List secondMock = Mockito.mock(List.class);
Mockito.when(mock.get(0)).thenReturn(secondMock);
}

No workarounds are necessary with Mockachino since it does not rely on ordering of calls.
Thus, the equivalent in Mockachino works fine:

@Test
public void testInlineMockachino() {
List mock = Mockachino.mock(List.class);
Mockachino.stubReturn(Mockachino.mock(List.class)).on(mock).get(0);
}
Calling mock methods when verifying
Another interesting case is this. Due to Mockitos design choice of letting calls to verify and stub apply to the most recently invoked mock method, the following case breaks, since verify will actually try to verify mock.size() instead of mock.add()

@Test
public void testMockito() {
List mock = Mockito.mock(List.class);
mock.add(0);
Mockito.verify(mock).add(mock.size());
}

It works fine in Mockachino, due to a different design choice:

@Test
public void testMockachino() {
List mock = Mockachino.mock(List.class);
mock.add(0);
Mockachino.verifyOnce().on(mock).add(mock.size());
}

Deep mocks
Update 2010-03-13 - Both the latest Mockito and Mockachino have deep mock handlers that behave in the same way.

Time ranges Mockachino supports verifying that interactions with a mock happened in a specific time range.
See additional-features-of-mockachino for a more detailed explanation.
Mockito does not include this feature.

Saturday, February 13, 2010

Additional features of Mockachino

Mockachino is making good progress!
Apart from generic refactorings, I've added a few nifty features:

Support for equals, hashCode and toString
Unlike EasyMock and Mockito, Mockachino now supports stubbing, verifying of all these methods. The other mocking frameworks probaby have good reasons for not supporting those. I at least know that Mockachino used to have good reasons. If you're not interested in the technical details, you can skip the next two paragraphs.

All mocks need some sort of data storage for their metadata. The metadata is basically just a memory of all invocations and a list of all stubbing definitions. This metadata needs to either be stored in the mock itself or use some sort of mapping strategy. I used to have a WeakHashMap that mapped the mocks to their metadata, and for that to work I required a fixed equals and hashCode.

My new approach is instead to let all my mocks implement a secondary interface which has a secret method for retrieving the metadata. The invocation handler for the mock simply listens for this method call and returns its reference to the metadata. It's really quite simple, and as with all simple ideas, you start to wonder why you didn't think of it before.

The problem with in order verification
One problem I had was in order verification of this sort:

@Test
public void test() {
List mock = mock(List.class);
mock.add(100);
mock.add(200);
mock.add(100);

OrderingContext ordering = newOrdering();
ordering.verifyAtMost(1).on(mock).add(100);
ordering.verifyAtLeast(1).on(mock).add(200);
}

By reading the entire ordering part, it seems that the test would pass, since there is only one call to add(100) before the call to add(200). But at the time of the first verification, it doesn't know when it should stop looking for more matches. This is easy to see when considering the next example:

@Test
public void test() {
List mock = mock(List.class);
mock.add(100);
mock.add(100);

OrderingContext ordering = newOrdering();
ordering.verifyAtMost(1).on(mock).add(100);
}

Here you obviously expect a failure since there were in fact two calls to add(100) when you expected at most one. For this reason, Mockachino doesn't support "at most"-matching for in order verifications.

So I started thinking about different approaches.
You could do something like this instead:

@Test
public void test() {
List mock = mock(List.class);
mock.add(100);
mock.add(200);
mock.add(100);

OrderingContext ordering = newOrdering();
ordering.verifyAtMost(1).on(mock).add(100);
ordering.verifyAtLeast(1).on(mock).add(200);
ordering.verifyOrdering();
}

Simply change the ordering concept to not verify anything at all until the call to verifyOrdering() is called. At this point you do have all the information you need.
The problem with this is that it adds a lot of complexity, both to the code base and to the tests. It's similar to solving a complex regular expression - it would need to backtrack on failures until it can be sure that it's impossible to satisfy the conditions.

It's simply not a clean solution. In practice such an ordering tests would be frail and be far to dependent on the internal state.

Adding "points in time" and time range verification.
Another way of supporting these kind of use cases is to add two new very simple constructs, that should rarely be needed, but be very useful and powerful in the few cases that you do.

The first construct is the MockPoint. This is simply a point in time that you can get in two different ways:

// 1
MockPoint point = Mockachino.getCurrentPoint();

// 2
OrderingContext order = Mockachino.newOrdering();
order.verifyOnce().on(mock).add();
MockPoint point = order.afterLastCall();

With these points, you can take advantage of the second construct: between, after and before
Simply add between(point1, point2) before your verification line to limit your matches to calls done between those points in time.

So instead of checking that something happened at most a certain number of times in order, grab the time points and verify it normally with between instead:


@Test
public void test() {
List mock = mock(List.class);
mock.add(100);
mock.add(200);
mock.add(100);

// Get the points
OrderingContext ordering = newOrdering();
MockPoint p1 = ordering.atLastCall();
ordering.verifyAtLeast(1).on(mock).add(200);
MockPoint p2 = ordering.beforeLastCall();

between(p1, p2).verifyAtMost(1).on(mock).add(100);
}

It's not as pretty as in the first example, but it works and is conceptually simple.
I don't recommend overusing this feature since it's probably in most cases a warning sign that your code is frail and makes too many assumptions.

Friday, February 12, 2010

The different types of tests

There is a huge number of examples of types of tests in the development community and they can be categorized in many different ways

I am going to focus on splitting tests by their intention here.
I guess people generally think of tests as a tool for reducing bugs and keeping robustness. Tests give us the courage to dare perform large refactorings and introduce new features while being relatively confident that we aren't breaking things.

That's a very important part of writing tests but I'll argue that there's another side to it:
Tests help us design. Tests help us write clean code. Tests help us split code into isolated modules.

With these two in mind, consider the following two test strategys: Unit Testing and Blackbox Testing.

Blackbox tests
my definition:
A blackbox test looks at the code as if it were a black box, i.e. the internals of the system are unknown and irrelevant. You use your knowledge of the system requirements to provide the inputs and verify that the outputs are correct.

I really like writing blackbox tests because they are fairly immune to internal refactorings and can usually quite easily capture the requirements on a high level. Blackbox tests have the additional benefit of being able to test a lot of code at once, and only testing code that will actually be used by real users.

However, writing blackbox tests on a too high level doesn't force you to write clean and modularized code.

Unit tests
my definition:
A unit test verifies the correctness of individual components of the system (hence the name unit). If the component (or unit) needs some collaborators, you typically mock them, and let them provide the inputs you want for your specific test. Unlike black box testing, you want to limit the scope of testing as much as possible per test.

Unit tests on the other hand usually have to be rewritten every time you perform refactorings and they can usually only capture requirements that are contained within a single class. The advantage of unit tests is that they force you to write your classes to be testable individually, which greatly helps you write good code.

Coverage
Some people like to measure the coverage of their codebase, and diligently write unit tests until they're at an acceptable level. I think that writing unit tests for the sake of increasing coverage is wrong.

The problem is that you're potentially testing dead code, and our only way of detecting dead code is by looking at coverage reports.

Instead, consider measuring coverage from blackbox tests and unit tests separately.
The blackbox tests should reflect the overall system requirements so run coverage for those tests. Then by looking at the coverage report you can spot dead code - Code that isn't used by any requirement.

If you spot any particular dead code section, you have two options:
  1. Remove the code - it isn't used! Dead code bloats down your codebase.
  2. If the code can't be removed, it must be a part of some requirement, so formalize the requirement as a blackbox test and try it again.
If you try writing a unit test just to exercise that code, you haven't gained anything, just a false sense of code coverage.

Conclusion
When developing according to TDD practices, should you write blackbox tests or unit tests?
The answer is both! I like to start with writing blackbox tests that cover all the requirements I can come up with. Then continue iteratively with unit tests and code in the usual TDD cycle until both the blackbox tests and unit tests are happy.

This should mean that you both capture the necessary requirement while maintaining a healthy code base.

When mocks fail

A mocking framework has three fundamental features:
  1. Makes it easy to stub behaviour to make your test code work.
  2. Makes it easy to verify that some behaviour has taken place.
  3. Makes it easy to debug a broken test.
Today I'll focus on the third part.

When a test fails, it either means that your code is wrong or your test is wrong.
Either way, you want to find the cause of the problem as quickly as possible.

To assist with this, mocking frameworks try to give you as much relevant information as possible when a verification fails.

EasyMock usually says something like:
@Test
public void testFailEasymock() {
List mock = createNiceMock(List.class);
expect(mock.add("Hello")).andReturn(true);
replay(mock);
mock.remove("World");
mock.remove("Hello");
mock.add(null);
mock.add("World");
verify(mock);
}

java.lang.AssertionError:
Expectation failure on verify:
add("Hello"): expected: 1, actual: 0


which tells you that add was expected, but never called.

Mockito is a bit nicer and shows what was actually called instead:
@Test
public void testFailMockito() {
List mock = mock(List.class);
mock.remove("World");
mock.remove("Hello");
mock.add(null);
mock.add("World");
verify(mock, atLeastOnce()).add("Hello");
}

Argument(s) are different! Wanted:
list.add("Hello");
-> at ordering.MixedOrderTest.testFailMockito(MixedOrderTest.java:95)
Actual invocation has different arguments:
list.add(null);
-> at ordering.MixedOrderTest.testFailMockito(MixedOrderTest.java:93)

Expected :list.add("Hello");
Actual :list.add(null);

Which is more helpful than EasyMock.

However, Mockito only suggests the first invocation of list.add as the actual invocation instead of the best matching.

Mockachino goes a step further and suggests the three best matching calls, sorted by how well it was matched:
@Test
public void testFailMockachino() {
List mock = mock(List.class);
mock.remove("World");
mock.remove("Hello");
mock.add(null);
mock.add("World");
verifyAtLeast(1).on(mock).add("Hello");
}

se.mockachino.exceptions.VerificationError: Expected at least 1 call but got no calls
Method pattern:
add("Hello")

Near matches:
add("World")
at se.mockachino.order.InOrderTest.testFailMockito(InOrderTest.java:116)
add(null)
at se.mockachino.order.InOrderTest.testFailMockito(InOrderTest.java:115)
remove("Hello")
at se.mockachino.order.InOrderTest.testFailMockito(InOrderTest.java:114)
... skipping 1 calls

at se.mockachino.order.InOrderTest.testFailMockito(InOrderTest.java:117)

As you can see, both Mockito and Mockachino show where the verification call was made,
and where the actual matches were made. This is really helpful if you run the tests in an IDE, just click on the lines to jump to the corresponding line in the code.

It's clear that EasyMock shows too little information here, but how much is too much?

Is the simple approach of Mockito to just show the first partially matching method call sufficient? Yes, it probably does cover most of the cases but I think it would be improved without adding any noise if it tried to do some smarter matching.

I think it's equally likely that a mock called the wrong method but with the correct parameters compared to calling the correct method but with the wrong parameters. I think the approach of showing multiple suggestions is a good one.

In conclusion I think that both Mockito and Mockachino do a good job of reporting failed verifications, and that Mockachino may have an advantage in debugging some use cases where the mockito suggestion is the wrong one.

Saturday, February 6, 2010

Followup on mocking frameworks for Java

So, a week has passed and my mocking framework is fairly complete for a first release. All the information can be found on http://code.google.com/p/mockachino/ I expect some slight API changes in the near future, adding a few more (but not many) features and fixing some bugs (though I have no known at this time).

I'd like to think that my experiment was a success, but how can I know how good it really is unless I get real users for it. It's a tricky situation. I personally think it has a better overall design than Mockito and mostly the same featureset, but generally you need to be significantly better for users to switch. I can't say I'm any different myself, why would I replace a library I use for a slightly better, if it would cost me time and effort to do so?

So there are a couple of issues I need to work on before I can have an actual userbase:

  1. Make it better than Mockito. This is by itself hard, since Mockito is already a very good mocking framework. Of all the mocking frameworks I've seen, it's by far superior. So I need to have all the features that Mockito has, plus a lot more.
  2. Figure out any realistic test usecases where Mockachino is better than Mockito. Given my knowledge of my own design and the design of Mockito, this should be doable to some extent at least.
  3. Make converting from Mockito to Mockachino easy. If you have a large codebase you don't want to manually rewrite all your tests to change framework. Maybe it is possible to write a small application that can convert existing java tests to use Mockachino instead of other frameworks (EasyMock, Mockito).
  4. Let people know it exists. This is hard. Word of mouth only goes so far. Some loose ideas include trying to make google rank the project site higher for relevant search terms, such as mocking and java. Also, I could inform tech bloggers that it exists so it can mentioned in articles that compare mocking frameworks.

Of course, the technical challenge is by itself worth something, and I definitely feel I have learned from it.

I guess I can sum up this entire entry in a single sentence.
If a code project falls in the internet forest and no one hears it, does it make a sound?

Sunday, January 31, 2010

Java and mocking frameworks

Frameworks such as Mockito can be extremely helpful when writing tests for your code. After having compared Mockito with EasyMock, it became very obvious that EasyMocks approach to mocking is just badly designed. The normal flow in Mockito is
  1. setup mocks
  2. stub the mocks to return useful values, in order to make your real code work.
  3. exercise your code using the mocks
  4. verify that the mocks have been called in appropiate ways
This is just the general approach, Mockito allows you to do more complex flows, such as setup, stub, exercise, verify, exercise some more, verify some more.
This design feels correct since the four parts of mocking are orthogonal.

EasyMock has quite a different approach:
  1. setup mocks and set global options for the mocks (verify in order or not, should the mocks be strict or nice)
  2. write expectations, which is a combination of verification and stubbing.
  3. exercise the code
  4. apply all predefined expectations for validation
This approach makes it harder to customize your tests, for situations when you only want to test ordering for parts of the methods, or only want some method calls to be strict or nice.
Strict and nice aren't even concepts in Mockito, since strictness is completely a consequence of writing your verification.

There are many more advantages to Mockito, such as easy to use API and very clean and helpful error messages and stacktraces.

Out of curiousity, I have tried writing my own mocking framework with Mockitos usage model in mind, but with other goals as well. I wanted my mocking framework to have an extremely clean design, even sacrificing some real world uses, which makes it less useful for testing legacy code, but probably equally useful for a modern test driven codebase.

I actively chose to not support mocking classes, just interfaces. There are two reasons for this:
all of your complex injected dependencies should be interfaces, not classes, so it's not a big downside for proper code. The second reason is that I wanted to avoid dependencies on bytecode manipulation libraries such as cglib or asm. I only use the Proxy class from java.lang.reflect instead.

It turns out that some aspects of mocking is more straight forward in my mocking framework than Mockito.
This is taken from the Mockito documentation: "If you are using argument matchers, all arguments have to be provided by matchers. "

My approach allows you to mix freely with one expection - you can't use both argument matchers and plain nulls or some magic numbers (like -107 for byte values, et.c.)

A second difference is this:

//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");

The equivalent code in my framework works just fine:

Mockachino.stubReturn(spy, "foo").get(0);

I have put up the source code on google code for all to see. It might survive to become a stable and usable codebase, or it may not. We'll see how long it can keep my interest. Things generally become less fun when all the big problems have been solved.

I almost forgot, here is the link:
http://code.google.com/p/mockachino/