Tag Archives: JUnit

Practical Unit Testing with TestNG and Mockito – by Tomek Kaczanowski


TL;DR This is an essential book on Unit Testing for both novice and experienced Java developer alike. Practical Unit Testing provides a well-paced and logical introduction into the world of Unit Testing, and also offers the more experienced practitioners a discussion on topics such as defining what to test and verify, how to write high-quality and maintainable tests, and also when (shock horror!) not to test. This book provides a plethora of examples and is extremely pragmatic in it’s delivery of testing in the real world. I would also strongly recommend this book to any JUnit fans that haven’t experimented with TestNG lately – you might be surprised what this framework now offers!

Practical Unit testing is divided into five primary sections: ‘Developer’s Tests’, ‘Writing Test’, ‘Hints and Discussion’, ‘Listen and Organise’ and ‘Make them better’. It’s worth mentioning here that this flavour of the book strongly focuses on using TestNG and Mockito (there is a JUnit flavoured version, Practical Unit Testing with JUnit and Mockito). As mentioned above, if you haven’t played with TestNG lately, I would recommend that you do (with this book by you side), as the framework has developed rapidly over the past few years into a genuine competitor against JUnit.

Section 1, ‘Developer’s Tests’, begins by discussing motivations and the core methodology behind testing in general. Unit testing is then defined and the basic concepts introduced to the reader. Section 2 begins by getting the reader to write their first tests, and introduces key concepts such as assertions and parameterised tests.

Section 2 of the book continues with Chapter 4, which introduces the reader to Test Driven Development (TDD), and IMHO this chapter should be read by all Java developers. The author presents an excellent discussion on when to write tests, the ‘rhythm’ of TDD and the benefits offered, and also provides concrete examples. This chapter even covers when not to use TDD, which I know can be heresy to some advocates, but as a long time practitioner of TDD I can relate to points made by the author in this chapter.

As with any technique (or philosophy) as powerful as TDD it is easy to become dogmatic about the subject, and ultimately forgot that not every problem can be solved with a single approach or solution. Paraphrasing the author, he suggests problem areas with applying TDD can include not having a good knowledge of the problem domain, not understanding the technologies, and when working on legacy code. In my experience, I have made several mistakes with applying TDD in the areas identified, and so the author’s cautions should be well received (on a related topic, I can highly recommend Working Effectively with Legacy Code (Robert C. Martin) when dealing with testing legacy code)

Next is very useful discussion Mocks, Stubs and Spies, which is obviously focused on Mockito (which is currently my Mocking framework of choice). As with all the concepts discussed in this book, the example code provided is very useful and of high quality. On a related topic, I would definitely recommend a read of the Mockito website in addition to the this chapter, as the website includes a vast array of examples, and is also updated often.

Section 3 of the book kicks off with Chapter 6, ‘Things You Should Know’, and this chapter is again essential reading. In fact I would go so far to say that this part of the book is worth the entry fee alone – it covers a lot very interesting topics, such as knowing what to test, isolating code under test, making tests timely, using external data and dealing with concurrency. It also discusses what the author refers to as ‘points of controversy’, such as limiting multiple assertions per test (the logical assertions debate) and private method testing.

The remaining two sections of the book focus on getting feedback from tests (and what to do with it), how to organise your tests, and also how to write maintainable high-quality tests. This was an often overlooked topic in a lot of the earlier TDD books, and the often (unspoken) implication was that test code doesn’t have to be as high-quality as ‘production’ code, which is obviously a complete fallacy. In my experience poorly written (and brittle) tests can often slow development down considerably, and this ultimately leads to tests being either removed or ignored…

In summary, this is an essential purchase for any Java developer serious about testing and TDD. For some reason, this book appears to be under the radar to a lot of TDD advocates, and I’m not sure why. The current favourite TDD book, of which I am also a huge fan of, is Effective Unit Testing: A guide for Java developers, and I believe this TestNG-focused book is a great complement to the JUnit-focused work presented in Effective Unit Testing. Practical Unit Testing provides a great introduction for developers new to TDD, and also offers experienced TDDers plenty to think about. The book is well-paced and logical in it’s approach, and provides a comprehensive approach to writing useful, high-quality and maintainable tests.

Click here to buy Practical Unit Testing with TestNG and Mockito on Amazon UK (This is a sponsored link. Please click through and help a fellow developer buy some more books!)

A recent contract I was working on had decided to use Solr to implement full-text search over a product catalogue for an e-commerce platform. Naturally we were approaching development with a TDD-mindset, and were keen to implement both Unit Tests for core business functionality, and also integration tests for for a more end-to-end style of testing. The primary application stack consists of Spring (Core, Data, MVC), MySQL and Solr 4.

Just a slight aside, but for anyone looking to implement full-text search the primary candidates are Solr and ElasticSearch. I won’t discuss the merits of either implementation further as it’s best to evaluate each in respect to your use cases (and here is an excellent resource to help you decide

With our chosen frameworks and datastores we found the Unit testing relatively straight-forward, and decided to use JUnit (driven via the Maven surefire plugin), Mockito for mocking external dependencies (persistence layer, API calls etc), and PowerMock for the difficult mocking (for example, mocking static method calls of several reliable-but-decidedly-old-skool dependencies).

Integration testing was also relatively easy to setup – we chose to again drive tests via JUnit (this time via the failsafe plugin), and use Spring’s @ContextConfiguration and AbstractTransactionalJUnit4SpringContextTests to manage injected sub-components (@Autowires etc) and instantiate various parts of the application for testing, and we also ran an embedded H2 database to allow realistic simulation of a SQL datastore (just an aside, in ~99% of ‘standard’ use cases I have found H2 to behave identically to MySQL, but there are a couple of corner cases to watch out for – this will be another blog post :))

The Problem – How do we run an embedded Solr?

When we first started using Solr 4 we naturally wanted to create integration tests running against this datastore, and we wanted to run this in the same manner as we did with H2 – executing as a light-weight in-memory (embedded) process that we could create, pre-load, and destroy relatively quickly.

We soon found the EmbeddedSolrServer Class distributed within the Solr package, and although useful it didn’t fit in exactly with the way we wanted to design and deploy the Solr communication layer within our Spring application. For production use we wanted to instantiate a SolrServer bean for which we supply the target endpoint on the network (and under the hood this SolrServer bean would actually be instantiated using a custom HttpSolrServer Class). We needed a way to create an ’embedded’ version that implemented the SolrServer interface, but also allowed us to override the Solr config and data directory (to load pre-canned indexes etc)

After a fair bit of searching we stumbled over ZoomInfo’s excellent blog in which they had shared their version of an embedded SolrServer that could easily be exposed as a Spring bean. They called the Class the InProcessSolrServer

We would like to offer many thanks to ZoomInfo for sharing there great work, and this Class provided us with many months of good service. However, with the latest releases of Solr (4.2 +) ZoomInfo’s InProcessSolrServer will no longer compile due to an interface change within the Solr internals.

In the spirit of sharing the wealth I wanted to blog an update to the original ZoomInfo code, which addresses the interface change, and I’ve also included the Spring scaffolding in the gist below to give you an idea of how we run this code.

I hope this helps, and if you have any questions then please feel free to comment or tweet 🙂