Tag: Tools

Key Software Factory Tools in the Java World

Here are some popular free and/or freemium tools for creating a software factory for a Java project :

I’ve written about these build tools before.

Here’s a chart showing the relative popularity of these 3 tools.

There are many more unit test facilitators available for free, and I’ve developed some lesser-known open-source unit test facilitators myself.

  • Integration test facilitators
    • Arquillian – allows you to run a test on a Java EE server (either a remote server or one configured and launched by your test code)
    • OpenEJB – a lightweight EJB framework implementation that can be launched in a test
    • DBUnit – set up and clean up after tests that use real database connections
    • Docker – actually, Docker is a facilitator for just about any sort of automation you want to do, but I put it in the integration test category because it allows you to spin up a database or other server from a test.

Note: do not mix the Arquillian and OpenEJB together in the same test suite – jar conflicts can ensue when tests are run manually in Eclipse

There are surely other tools I’ve left out.  Feel free to mention your favorites in the comments.

Advertisements

Software factories

In the real world, most of us are not quite there, but it’s now possible with only free tools to have a reliable product release process which consists of just developing and committing code. In the case of an editor releasing a versioned software product, or for a site where new features are released gradually or via AB testing, or in all cases where human testers and/or management approval are necessary, there would also have to be the click of a button to approve a release. I’m speaking in broad, hand-waving generality, but such a process, when achieved, can provide a competitive advantage to a product or site by reducing time-to-market for new features and reducing the risk of quality issues (translation: easier to develop faster with fewer bugs).

Of course setting up such a process requires a lot of up-front work, considerable expertise, and occasional maintenance down the road, and such a system will (by design, normally) come to a halt very quickly if it is fed anything other than clean, well-tested code.

This notion has been called a “software factory” or “continuous delivery” or “continuous deployment” system.

I’ll have more to say on this subject soon, but today I will just point you to a couple of interesting diagrams:

Java build tools: Ant, Maven or Gradle?

When you create a java project (for a library or an application or a web site), while you could just rely on your IDE to build things for you, in most cases you really need a build script. For a build script, you basically have 3 choices: Ant, Maven or Gradle.

Now that I’ve used all three of these tools, thought I’d share some thoughts about how to choose between them. This is not an article about how to migrate from one of them to another – that’s usually not worth the pain if your build is complicated, and it’s fairly trivial if your build is very simple.

In the context of a new project, let’s take a look at each of the choices:

Ant

Ant is the old-school tool. Your build script is basically a list of configured commands in XML, organized as a set of interdependent tasks. It’s easy to learn, and relatively easy to debug. It’s pretty easy to extend with custom tags implemented in Java (I’ve created one myself). Ant does not naturally include dependency management (loading external jar files), bit that can be added with Apache Ivy.

Strong points:

  • easy to learn
  • easy to understand
  • excellent integration in IDE’s
  • lots of examples and help online

Weak points:

  • Procedural (build scripts can get very complicated)
  • inelegant
  • For dependency management, Ivy is less intuitive and requires extra configuration and tooling

Maven

Maven is the opinionated tool which forces a project structure and build life cycle on you, and it’s also the tool that introduced built-in dependency management and a central repository for dependencies. Like Ant, it’s based on XML. Some people hate Maven for making them do things Maven’s way, but the benefit is simplicity. Unlike with Ant and Gradle scripts, two Maven scripts which do roughly the same thing are very similar. I have not tried to extend its functionality, but Maven has a plugin architecture, and a lot of useful plugins are available. Maven is also well-integrated in a number of popular tools.

Strong points:

  • generally very little thought or debugging required to get a typical build working
  • strong integration with various CI and IDE tools
  • simple dependency management
  • lots of examples and explanations online

Weak points:

  • Lots of pain if you don’t organize your project the Maven way
  • inelegant

Gradle

A relative newcomer, Gradle offers an elegant groovy-based DSL to run your build. Like Maven, Gradle has built-in dependency-management and makes some assumptions about project structure, but like Ant its execution is based on tasks. Unlike both Ant and Maven, Gradle has an elegant syntax which allows you to essentially write your build code in Groovy. Unlike Maven, the assumptions about project structure are conventions rather than rules. I have to say, though, that I recently encountered an official Gradle plugin which takes some of those assumptions as hard rules, and I had to abandon the plugin and use another tool. Hopefully this situation will improve over time. One thing I really like about Gradle is its dependency management syntax, which allows much simpler find-replace for version upgrades than Maven’s XML tags. The library name and version are all together on one line.

Strong points:

  • Elegance (i.e. lack of XML tags)
  • flexibility
  • simple dependency management
  • concision

Weak points:

  • Immature tooling and immature integration with popular tools (CI, IDE)
  • limited examples and help online
  • steep learning curve (especially for Groovy noobs)
  • inflexible plugins.

Conclusion

All three of these tools are good tools which can get the job done if you know what you’re doing. Personally, for a new Java project, I’d chose Maven for basic building of jar and war files. It’s what I did choose, even for my open-source Ant plugin. I Ant also, for non-build tasks (mass file copying with text replacement, for example) and tasks around the builds (for example, to update versions of dependency libraries and to rebuild the delegate interfaces using interface-it ant). Gradle is a very elegant and promising tool which will surely resolve some of its weak points over time. If you’re comfortable with groovy, it might be the right choice for you, but only if you stick to their recommended multi-project structure and don’t lean too heavily on your IDE.

What are you building?

A project, a product, or a brand?

Actually, luck has played a big role in our industry, and sometimes you don’t know what you’re building until later. I could have called this post “What’s in a name?” or “Why I have to work around MySQL performance bugs when there’s at least one technically superior and totally free database we could have used instead.”

This is a story of well-meaning people who made what seemed like reasonable choices at the time, some of which have caused mild suffering. They say the road to hell is paved with good intentions.

So what’s in a name? In the 1980’s if you’re a geeky professor creating a project to replace the “Ingres” database project, “Postgres” sounds like a pretty clever name. If SQL becomes a popular standard and is now supported, changing “Postgres” to “PostgreSQL” also seems pretty sensible. There’s continuity. The handful of students who used it at the time were not confused at all. But even for them it might have been better to choose the name of a painter more recent than Ingres (DegaSQL, MatisSQL, PicasSQL, KandinSQL, MonetSQL, RenoirDB, SeuratSQL, DaliBase?).

Then there’s MySQL. Sigh. Maybe we’re all shallow, narcissistic people at heart, or maybe we all just follow the orders of people who are, but “MySQL” is a near-perfect brand name because it’s all about “me“, and it’s “mine”. No need to explain what’s up with the name. Sold. Add to that a focus on the needs of ISP’s and Linux users, and it becomes second only to Oracle in popularity. PostgreSQL is in 4th place now, but the usage scores drop off a cliff after 3rd place (which is Microsoft SQL Server).

It turns out, though, that the brilliant name choice of “MySQL” was just as random as the awful name chosen for its competitor. “Monty” Widenus named MySQL after his first daughter, My. By the way, more-actively-maintained-and-improved fork of MySQL, languishing in 20th place in usage rankings, is MariaDB, named after his second daughter. If he’d had only one daughter, named Ingrid instead of My, the fork might have been called “PostgridSQL”.

So, do I have a point? Just that you might want to think when you create something about who it’s for and to think, when naming or re-branding it, about how people who are not currently “in the loop” will perceive it. Also, if your technology is really solid and well-designed, please be lucky.

For info, recent database usage rankings from db-engines.com:

1. Oracle Relational DBMS 1449.25
2. MySQL  Relational DBMS 1370.13
3. Microsoft SQL Server Relational DBMS 1165.81
4. MongoDB  Document store 314.62
5. PostgreSQL Relational DBMS 306.60
6. DB2 Relational DBMS 188.57
7. Cassandra  Wide column store 131.12
8. Microsoft Access Relational DBMS 126.22
9. SQLite Relational DBMS 106.78
10. Redis  Key-value store 104.49
11. Elasticsearch  Search engine 87.41
20. MariaDB Relational DBMS 34.66

 

Improved matching error messages in Extended-Mockito

I’ve recently made some improvements to Extended-Mockito in the area of failure messages.

In early versions, messages from a failure to match in a verify() call were a bit cryptic, especially when matching based on lambdas.  This is what you used to get :

Wanted but not invoked:
exampleService.doAThingWithSomeParameters(
    <Extended matchers$$ lambda$ 6/ 1 5 0 2 6 8 5 4 0>,
    <Extended matchers$$ lambda$ 8/ 3 6 1 5 7 1 9 6 8>,
    <custom argument matcher>,
    <Extended matchers$$ lambda$ 1 1/ 2 1 0 5 0 6 4 1 2>
);

In the first of my examples with the new improvements (available starting in version 2.0.78-beta.1 of extended-mockito and transitively in version 0.9.0 of tdd-mixins-core and tdd-mixins-junit4 ) it’s now possible to show more clearly what kind of arguments were expected:

Wanted but not invoked:
exampleService.doAThingWithSomeParameters(
{String containing all of: [Butcher,Baker,Candlestick Maker]},
[All items matching the given Predicate],
[One or more items matching the given Predicate],
SomeBean where val1 > 5
);

For info, the expectation call which gives this failure message is:

verify(expecting).doAThingWithSomeParameters(this.containsAllOf("Butcher", "Baker", "Candlestick Maker"),
				allSetItemsMatch(s -> s.startsWith("A")),
				oneOrMoreListItemsMatch(s -> s.startsWith("B")),
				objectMatches((SomeBean o) -> o.getVal1() > 5, "SomeBean where val1 > 5"));

Does TDD “damage” your design?

I recently came across a couple articles that challenged some of my beliefs about best practices.

In this article, Simon Brown makes the case for components tightly coupling a service with its data access implementation and for testing each component as a unit rather than testing the service with mocked-out data access. Brown also cites David Heinemeir Hansson, the creator of Rails, who has written a couple of incendiary articles discouraging isolated tests and even TDD in general. Heinemeir Hansson goes so far as to suggest that TDD results in “code that is warped out of shape solely to accomodate testing objectives.Ouch.

These are thought-provoking articles written by smart, accomplished engineers, but I disagree with them.

For those unfamiliar with the (volatile and sometimes confusing and controversial) terminology, isolated tests are tests which mock out dependencies of the unit under test. This is done both for performance reasons (which Heinemeir Hansson calls into question) and for focus on the unit (if a service calls the database and the test fails, is the problem in the service or the SQL or the database tables or the network connection?). There’s also a question of the difficulty of setting up and maintaining tests with database dependencies. There are tools for that, but there’s a learning curve and some set-up required (which hopefully can be Dockerized to make life easier). And there’s one more very important reason which I’ll get to later…

Both Brown and Heinemeir Hansson argue against adding what they consider unnecessary layers of indirection. If your design is test-driven, the need for unit tests will nudge you to de-couple things that Brown and Heinemeir Hansson think should remain coupled. The real dilemma is where should we put the inevitable complexity in any design? As an extreme example, to avoid all sorts of “unnecessary” code you could just put all your business logic into stored procedures in the database.

“Gang of Four” member Ralph Johnson described a paradox:

There is no theoretical reason that anything is hard to change about software. If you pick any one aspect of software then you can make it easy to change, but we don’t know how to make everything easy to change. Making something easy to change makes the overall system a little more complex, and making everything easy to change makes the entire system very complex. Complexity is what makes software hard to change. That, and duplication.

TDD, especially the “mockist” variety, nudges us to add layers of indirection to separate responsibilities cleanly. Johnson seems to be implying that doing this systematically can add unnecessary complexity to the system, making it harder to change, paradoxically undermining one of TDD’s goals.

I do not think that lots of loose coupling makes things harder to change. It does increase the number of interfaces, but it makes it easier to swap out implementations or to limit behavior changes to a single class.

And what about the complexity of the test code? Brown and Heinemeir Hansson seem to act as if reducing the complexity of the test code does not matter. Or rather, that you don’t need to write tests for code that’s hard to test because you should just expand the scope of the tests to do verification at the level of whole components.

Here’s where I get back to that other important reason why “isolated” tests are necessary: math. J.B. Rainsberger simply destroys the arguments of the kind that Brown and Heinemeir Hansson make and their emphasis on component-level tests. He points out that there’s an explosive multiplicative effect on the number of tests needed when you test classes in combination. For an oversimplified example, if your service class has 10 execution paths and its calls to your storage class have 10 execution paths on average, testing them as a component, you may need to write as may as 100 tests to get full coverage of the component. Testing them as separate units, you only need 20 tests to get the same coverage. Imagine your component has 10 interdependent classes like that… Do you have the developer bandwidth to write all those tests? If you do write them all, how easy is it to change something in your component? How many of those tests will break if you make one simple change?

So I reject the idea that TDD “damages” the design. If you think TDD would damage your design, maybe you just don’t know how bad your design is, because most of your code is not really tested.

As for Heinemeir Hansson’s contention that it’s outdated thinking to isolate tests from database access, he may be right about performance issues (not everyone has expensive development machines with fancy SSD drives, but there should be a way to run a modest number of database tests quickly). If a class’s single responsibility is closely linked to the database, I’m in favor of unit-testing it against a real database, but any other test that hits a real database should be considered an integration test. Brown proposes a re-shaped, “architecturally-aligned” testing pyramid with fewer unit tests and more integrated component tests. Because of the aforementioned combinatorial effect of coupling classes in the component, that approach would seem to require either writing (and frequently running) a lot more tests or releasing components which are not exhaustively tested.

A Testing Toolbox for Java 8

A few months ago, I presented interface-it, a java-8 tool to generate mixin interfaces. In case you don’t know what that means or why mixins could be useful to you, I wrote a short article which explains it.

One of the key motivations for the interface-it tool was to be able to generate mixins for the latest versions of unit-testing libraries like Mockito and AssertJ. Now you no longer have to worry about that, because I’m doing it for you. And more.

I now have several more projects to present to you.

Presenting tdd-mixins-junit4

Working backwards – if you want to have a great test fixture by adding only one dependency in your build configuration (your Maven Pom, Ivy xml, Gradle, or just a fat jar added to your classpath), use tdd-mixins-junit4. It gives you all the basics you need to do mocking and assertions with fluidity, simplicity and power.

Normally, that’s all you should need for your tests. Mockito allows you to to set up collaborating objects and verify behavior, and the extensions I added make it even easier to handle cases where, for example, you want to mock behavior based on arguments passed to the mock which are generated by your unit under test. As for verifying returned results, AssertJ and JUnit assertions allow you to verify any data returned by the unit under test.

Presenting tdd-mixins-core

If you do not want to use JUnit 4 (maybe you want to use TestNG or an early version of JUnit 5), then you can use tdd-mixins-core, which has everything that tdd-mixins-junit4 has, except the mixin for JUnit assertions and JUnit itself.

Presenting extended-mockito

So these tdd-mixins libraries notably give you mixins for the aforementioned libraries Mockito and AssertJ. As for Mockito, they use my extended-mockito (TODO: link to project) library, which not only provides mixins for classes like Mockito and BDDMockito, but it also provides extra matcher methods to simplify specifying matching arguments for mocked methods. For example:

when(myMockSpamFilter.isSpam(containsOneOrMoreOf("Viagra", "Cialis", "Payday loan")))
            .thenReturn(Boolean.TRUE);

See the project’s home page or the unit tests for more details.

Presenting template-example

As for AssertJ, it’s already quite extended for general purpose use, so there is no extended-assertj project, but if you want to take things farther, I did create a project called template-example, which shows how, with a little tweaking, you can use a Maven plugin to auto-generate custom assertions for your own JavaBeans which are combined with the AssertJ mixin from tdd-mixins-core. These custom assertions allow you to do smooth, fluent assertions for your own data types, allowing this sort of validation call:

assertThat(employee).employer().address().postalCode().startsWith("11");

With these tools, you can more productively write unit tests with powerful assertions and mocking. They give you a fixture that you can set up in any test class by implementing an interface or two – for example:

public class MyTest implements ExtendedMockito, AllAssertions {

Not Included

What’s missing from these tools? I wanted to keep the toolset light, so there are some excellent but more specialized tools which are not included. For example, I have generated a mixin for Jsoup, which is very useful if you need to validate generated HTML, but unless I hear a clamoring for it, I will leave it out of tdd-mixins-core because it adds a dependency that lots of people may not need. Same for extensions to AssertJ – I generated mixins for AssertJ-DB  and for AssertJGuava (UPDATE: also added one for Awaitility), but did not include them in tdd-mixins (you can copy and paste the generated mixins’ source files if you want to use them).

Another library which is useful but which does not lend itself to mixins (because it uses annotations rather than static calls) is Zohhak it simplifies testing methods which return results that depend on a wide variety of possible input values (such as mathematical calculations or business rules).

Presenting interface-it

I’m proud to introduce to you a new tool I created. It’s called interface-it, and it’s an open source project hosted on Github designed to help Java developers to create better test fixtures and to refactor procedural code more easily. More specifically, it’s designed to replace the use of static imports by the use of “mixin” interfaces.

What’s a “mixin”?

A mixin is basically a special kind of class which allows multiple inheritance without potential for unresolvable ambiguity or cycles in the inheritance hierarchy. It provides not just inheritance of the type but also of the implementation. Another word for “mixin”, used in the Scala language, is “trait”.

Before version 8, Java did not allow mixins, but now in Java 8 you can create an interface with default method implementations. Oracle does not especially encourage the use of default method implementations in interfaces – it’s a feature which was added in order to retrofit existing API’s with lambdas (as explained here). However, default methods can be quite useful in certain specific cases.

What’s wrong with static imports?

The site javapractices.com encourages us to “use static imports rarely” because they can make the code more difficult to understand. I’ve even worked in a team which had IDE settings to forbid the use of static imports. When you read code, it’s nice to know whether a method call is defined in the calling class or in another class, and whether it’s a static method or non-static. Static imports hide this information.

Use cases for interface-it

  • Test fixtures

There are tools like Mockito and AssertJ which encourage the use of many static calls in unit test code. You can either use static imports for these and hope your IDE’s auto-completion is up to the task of dealing with them. Or you can wrap the classes with these static methods using interface-it to create mixins used by your test class. In that case, you have no need for a static import (instead you have “class MyTestClass implements Mockito, AssertJ”), and you call methods of these tests tools as though they belong to your test class, because they do belong to it.

Before Java 8, to build a complex test fixture, you needed to create a superclass with all the functionality you might need in your tests, or a hierarchy of fixture classes with added layers of functionality in each subclass. In Java 8 you can use mixins to separate out different functionalities needed for different types of tests, and you can pick and choose which ones each test class needs to implement. Maybe some tests need to implement AssertJ but not Mockito, for example.

The interface-it tool can be used to create mixins for test fixture classes. You can also just copy and paste the example source code for Mockito and/or AssertJ generated by interface-it.

For interface-it’s own test fixtures, I’ve been “eating my own dog food”, so you can see an example of this in the DelegateMethodGeneratorTest class, which “implements AssertJ, Mockito, JUnitAssert” (note that I had to resolve a name conflict between AssertJ and JUnit – the method fail() –  by overriding one of the mixin methods – not a big deal in this case, but I also could have chosen to rename one of the fail() methods in the mixin source code if I had needed to call both methods).

  • Refactoring procedural legacy code

Static methods are not object-oriented. A static call enforces tight coupling, which constrains your design. You can replace an object by another object without modifying the code that uses the object, but a static call links one class to another which can not be replaced (note that some tools like Powermock can use some class loading voodoo to allow you to replace a static call in a test, but that does not fix the inherent design flaw).

In test fixtures, some procedural code is okay, because the tests are generally not reusable objects. Common functionality of different tests can be factored up, but unit tests are largely procedural in nature : setup (“given”), followed by invocation of the unit under test (“when”), followed by validation of results and post-conditions (“then”).

In production code, it’s better to avoid procedural code apart from some factory functionality (where you construct the graph of objects). There’s a lot of legacy production code in the world where a static method is called many times in many different classes. In this case, it’s quite painful to get rid of all these calls at once. Following the Boy Scout Rule, if you need to add one of these calls in the code that you’re working on, or if you are refactoring a class which makes procedural static calls, consider using interface-it to create a mixin which you can use to replace the static call in one place at a time. It’s also useful if you need to write a unit test before doing a more complete refactoring, because the mixin can be mocked in a test. In production code, you don’t necessarily have to have your legacy class implement the mixin as in the test fixture use case. You can simply treat the mixin as the interface of a collaborating object and pass it into the constructor or into specific methods where it’s needed. Where you need to instantiate it in production code, you can create an anonymous subclass, as in “new MyMixin() {}”.

Example usage in refactoring of legacy code:

Imagine we have a supply system which makes online credit card purchases automatically, and the call which does this is a static procedural call.  We want to add flexibility to the design and add unit tests so we can more easily manage code quality and refactorings, but we have these unavoidable static calls everywhere.  We have to start somewhere, so let’s fix SupplyMonitor‘s trackAndProcurePencils() method which checks the inventory of pencils against the number of employees and buys new pencils accordingly:

public void trackAndProcurePencils() {
    int targetPencilCount = this.currentEmployeeCount * TARGET_PENCILS_PER_EMPLOYEE;
    int currentPencilCount = inventory.getItemCount(PENCIL_ITEM_CODE);
    if (currentPencilCount < targetPencilCount) {
        SupplySystem.buy(new PurchaseOrder(PENCIL_ITEM_CODE, targetPencilCount -                  
            currentPencilCount), new CreditCard(CREDIT_CARD_NUMBER));
    }
}

So let’s write a unit test:

@Test
public void should_order_pencils_when_undersupplied() {
    Mockito.when(inventory.getItemCount(SupplyMonitor.PENCIL_ITEM_CODE)).thenReturn(120);
    underTest.trackAndProcurePencils();
    // Oh, dear. Not only to I have no way to test what happened inside the
    // method under test, but I think I just bought 280 pencils with my credit card!!!!
}

Better not commit that – it could get expensive.

We’re going to fix this by generating a wrapper interface which delegates to SupplySystem. In a Windows command-line we type:

C:\dev\eclipsews>java -cp SupplyProject\bin;interface-it\target\interface-it-0.7.0.jar org.interfaceit.ui.commandline.CommandLineMain -n SupplySystemWrapper -c org.legacy.SupplySystem -p org.legacy -d Katas\src\org\legacy -s SupplyProject\src\org\legacy\SupplySystem.java

…and see:

Wrote file: C:\dev\eclipsews\SupplyProject\src\org\legacy\SupplySystemWrapper.java

Now we have our generated wrapper interface. We update the test to look like this:

@Test
public void should_order_pencils_when_undersupplied() {
    Mockito.when(inventory.getItemCount(SupplyMonitor.PENCIL_ITEM_CODE)).thenReturn(120);
    underTest.trackAndProcurePencils();
    Mockito.verify(supplySystem).buy(Mockito.argThat(orderMatcher ), Mockito.any());
}

Note that we could also use interface-it to get rid of the “Mockito.” references in the test code (as previously demonstrated), but it’s better to focus one issue at a time.

Here are links to more complete code for the examples: before refactoring and after refactoring. The generated wrapper interface code can be found here.

Conclusion:

So that’s what interface-it can do for now.  I’ve already started work on improving usability by creating a custom Ant task that manages the generation and update of wrapper interfaces.  Since the jar is available on the Central Repository, anyone with Maven, Gradle or Ivy can easily pull the jar to create their own custom usability solution. If you’re looking for a project, you could use the interface-it jar to create a plugin for your favorite IDE (please leave a comment if you plan to do something like that). You can code whatever UI you want using the ClassCodeGenerator API, specifically by using an instance of DelegateMethodGenerator.

Gentle Introduction: Mockito

From time to time I will write an article aimed at introducing a tool or a concept to newbies, under the category “Gentle Introduction”. Since development technologies evolve quickly, you’re surely a newbie at something even if you’re a brilliant, accomplished developer.

Here I present the mock object framework Mockito.

Why do you need it?

For most of your unit tests (unit tests which are not integration tests – I’m still struggling to find exactly the right term to make this clear), you need to isolate the unit under test from everything external (so, for example, your suite of 500 tests can verify the logic of your code in 1 minute instead of wasting 20 minutes on calls to the database which are unnecessary for testing the logic).  You could do this by writing a stub class for every collaborator, but that’s an unwieldy approach, and you may find yourself spending more and more time maintaining a bunch of stubs as API’s evolve. A test double library like Mockito saves time and helps you write better, clearer, focused tests which run fast and are easier to maintain.

Why I chose Mockito

I used to use JMock as a mock objects framework, but I prefer Mockito because of its clearer syntax, its clear separation of stubbing and verification functionalities, and the fact that by default it ignores interactions which are not explicitly stubbed or verified (whereas with JMock adding a new interaction will almost always break your test).

What you can do with Mockito

The Mockito javadoc provides a lot of good introductory examples, but here’s a basic example to show what Mockito can do. It’s a piece of a TODO list service.  The full example code (which runs with JUnit 4) is available in a pastebin file. Below we see a test to verify a service method that delays by 1 day the deadline for a TODO item.  Using Mockito.when(), we set up the call which retrieves the item from storage to return a known value (this is known as stubbing), and we do verification (using Mockito.verify()) that the new deadline is correctly passed to storage:

	
@Test
public void can_delay_by_one_day() throws UnknownIdException {
	// Given:
	LocalDateTime originalDeadline = LocalDateTime.of(2016, Month.MARCH,
			20, 8, 00);
	// Stub the call to getById to return a known value
	Mockito.when(storage.getById(ITEM_ID)).thenReturn(
			new TodoItem(ITEM_ID, "Blog article", originalDeadline));

	// When:
	this.underTest.delayByOneDay(ITEM_ID);

	// Then:
	// Verify that the storage interface is called with the correct
	// arguments
	Mockito.verify(this.storage).updateDeadline(ITEM_ID,
			LocalDateTime.of(2016, Month.MARCH, 21, 8, 00));
}

If you use static imports, you’ll get code that looks more like:

verify(storage).updateDeadline(ITEM_ID, of(2016, MARCH, 21, 8, 00));

Here’s an example where we stub the storage retrieval method to throw an exception to verify that it’s not caught and swallowed by the service method:

	
@Test(expected = UnknownIdException.class)
public void should_pass_on_unknown_id_exception() throws UnknownIdException {
	// Given:
	Mockito.when(storage.getById(ITEM_ID)).thenThrow(
			new UnknownIdException(3L));
	
	// When:
	this.underTest.delayByOneDay(ITEM_ID);

	// Then: expect exception
}

More stuff you should know

If you understood everything up to here (stubbing to return a value, stubbing to throw an exception, and verifying a call with specific arguments), you know more than half of what you need to understand about Mockito to get a lot of value from it. It’s also important to know about matchers. If you have to verify a call but either do not know (or care about) or do not have access to an argument which will be passed, you can use matchers to cover the case you need to cover.  If you use a matcher for one argument of a call, you need to use it for all the arguments, so the Matchers class (as well as its subclass Mockito) contains a bunch of standard matchers like eq() and anyObject() for simple cases, and argThat() which allows you to use a more complex custom matcher.

You should know that stubbing void methods is a bit different.  Instead of calling

Mockito.when(myMock.voidMethod(arg0))...

you need to call:

Mockito.doAnswer(...).when(myMock).voidMethod(arg0);

There’s a nice explanation of this on StackOverflow.

You also need to know about Mockito.verifyNoMoreInteractions() in case you want the test to fail when there’s an unforeseen interaction with a particular mocked collaborator. There are also argument capturing (extracting arguments passed to mocked calls for later comparison or other analysis) and spies (partial mocking of real objects), which could be useful in certain cases.

Also, if you prefer a BDD-style approach to tests, and it bothers you to call when() in your “given” section, the class BDDMockito is for you.  It renames the “when” and “verify” methods to “given” and “then”.

Caveats and Limits

One caveat: I do not recommend using the auto-wiring annotations available with Mockito.  There are known limitations to the @InjectMocks annotation (as described here and here), which create some confusion and encourage questionable design practices.  Better to explicitly create and pass around mock objects. It makes your dependencies more visible, which is good design. Using @Mock (which is a factory annotation for a field of a class which is a mock) might save you a few keystrokes if you have a lot of mocks in one class, but you must either use Mockito’s test runner (JUnit allows only 1 test runner per class, and I think some are more useful than Mockito’s) or call MockitoAnnotations.initMocks(this) in your setup(), so unless you have a lot of mocks in one test class (which might be a code smell) I don’t think it’s worth it.

Mockito is based on a low-level proxy library (cglib or ByteBuddy, depending on the version of Mockito), which means that there are some limits to what it can do, but those limits are generally conducive to good design.  For example, Mockito, unlike PowerMock or JMockit, can not mock static methods.  If you’re developing new code, this is a good thing.  For legacy code, my goal would be to get to the point where the test code works with Mockito only, even if I have to use PowerMock to test things before refactoring.  Mockito can’t mock final classes or methods, either, but that’s another limitation which can be overcome by improving your design.

Mockito can mock concrete classes, but normally you should be mocking mostly interfaces.  If you follow the dependency inversion principle religiously, you can test the logic in your classes mocking only interfaces and maybe some abstract classes.  For concrete classes you don’t own, you can mock them, but it’s generally encouraged to wrap them in an abstraction with an interface that you do own and can mock instead.

I tested the example code above with Mockito versions 2.0.2-beta and 2.0.36-beta. Note that 2.0.36-beta has some breaking changes vis-à-vis earlier versions where matchers are concerned, though the workarounds for these are pretty easy. The example code here runs on both versions without any changes.

How to get Mockito

To try Mockito, you can download the 2.0.2-beta mockito-all fat jar from bintray.com, though you’d be better off using a tool like maven (or gradle or ivy) to automatically download. For the latest beta (currently 2.0.40), there is no fat jar – you will need mockito-core and the separate dependency jars – so a dependency manager tool like maven is even more useful.