Ok, I admit it. I really like automated testing.
In the beginning, they tell us that we're meeting the requirements, at least as well as we understand them. Along the way, they validate that nontrivial code we are writing isn't hiding a bug that will surely be found by a user at the most inopportune time. Long after the code is created and committed, they allow us to test new features. Alas, when bugs do scurry out of the darkness into the light of our user's monitor, automated tests help us verify the bug and its fix. Most importantly, they give us the confidence to refactor code to make it better. (It's axiomatic that the first edition of code written under a tight schedule can be improved upon!)
Not all tests are equal though.
Automated functional (i.e. web) testing tends to be tedious to write and is a little fragile in a changing business environment. Of course, starting and restarting a server drains our development momentum.
Integration tests are a bit better, but still impose time-wasting server starts, Spring context loading, database preparation, etc.
Pure unit tests are a different matter altogether.
Clean and fast, they tell us right away (in under 50ms) that the thing we're testing is doing what we think it should do. No servers to start up. No Spring context to load. We're in and out after just a few minutes of test code writing and 50ms of test execution.
One testing reality we have to deal with is that classes under test usually have collaborators. We're lucky if the collaborators are even available as they are often under parallel development. If they are, maybe they're being looked up (i.e. via JNDI) or, in the worst case, are being instantiated in the middle of a method we're testing. Our class under test relies on the collaborator's behavior and resulting data so the collaborators have to be accounted for by our test. Unaware of other options, we might just give in and make our speedy unit tests into slow integration tests to give us access to the collaborators.
But we do have other options.
This presentation is all about keeping unit tests pure unit tests.
First, we'll discuss some general testing concepts and coding pitfalls that we can avoid to help us in our effort. We'll also discuss challenges when creating tests for existing code that's poorly written and difficult to test. Then we'll dive into using Mocks and Stubs, what they are, how to write them, and why you shouldn't write them. Instead, I'll show you three Java mocking frameworks you should consider, with emphasis on Mockito, one of the new kids on the block. Throughout the presentation, I'll show you code that illustrates the concepts being discussed. In summary, we'll cover:
- Overview of automated testing
- Creating tests for badly written code
- Coding pitfalls to avoid that also make testing easier
- Mocks and Stubs
- Using a mocking frameworks - a brief look at jMock and EasyMock
- Introduction to Mockito
Speaker: Jack Frosch
Sponsor: TransITions