How do you encourage your team to write more unit tests?

You're part of a team where everyone understands and agrees unit tests are important and sees their value. Yet somehow you never get around to writing them. So how do you get out of this? How do you get from a situation where tests are an afterthought to one where writing unit tests is part of the team's culture?

Help build skills in the team

Most of the times people don't write unit tests because they get stuck very early along the way. You need to setup mocking. You need to create fixtures. You need to think of a lot of things.

Having someone a bit more experienced in the team that can setup the structure can make for a great example for the other team members. Also, pair programming on features and writing the tests together can also help in understanding how to think about the tests and how to design the code to be more testable.

Now, if no one in the team already has this experience, you don't need to dispair just yet :) Reading a good book on testing, like "Working effectively with legacy code" can also bring everyone up to speed with good testing practices.

Make unit tests part of your daily process

Are you already using JIRA or a similar issue tracking system? If yes, great! Make sure to add a subtask for each story specifically for writing the unit tests.

Are you already doing code reviews? Even better. Encourage your team to not merge any pull request unless the code change also has a test with it.

This will be hard at first. And it will slow you down. But it will make sure everyone is consistently practicing to write unit tests, getting better at it and with time, everything will get easier.

Visualize your progress

When you're focused on building features every sprint, it's easy to lose track of how far you've gotten with testing. One way to fix this is to visualize the code coverage of your application and see it increase over time. You could even celebrate once you reach certain milestones, like 30% or 40% coverage with a nice lunch together or going out for beers!

One tool I've used successfully for this is SonarQube. This is a code analysis tool that has some really nice features for code coverage. I really like the history time machine and the treemap. You can see how these look in this overview of how to manage the code coverage:

And even if it was built in Java for Java initially, it can actually analzye code coverage reports for a lot of other languages (like JavaScript, PHP and even Objective C).