Introduce test-driven development.
TDD and agile methods of development are very popular at the minute, and for good reason — you know, ahead of time, exactly what each part of the program must achieve, and you can confidently say that the program will work as intended as long as your tests are thorough.
I think that sometimes, the confusion begins when students aren't actually sure what they're trying to achieve in the first place, so they're reluctant to test because the code is already so fragile. TDD helps to ensure that there is a clear specification of behaviour for the code, so the students are clear on what should happen, and that the code they're written fulfils the specification.
Make it clear that testing is part of the project in your lessons, and it should help to solve some problems. When students are asked to write a program, they may not realise that writing some tests along with the project (or even beforehand, as in TDD) is a good idea. Having the red-green-refactor cycle would seem helpful here; it will give your students confidence that their code works as intended, and then the ability to clean up and improve their code without breaking it.
Test-Driven Development Goes To School was interesting reading while I wrote this answer. They evaluated the effects of teaching using TDD at several university courses, with generally mixed/positive results. At Virginia Polytechnic Institute:
- Code correctness measured as the number of defects per
thousand lines of code was only 38 for the TDD group compared to 70 for those not using
test-driven development
- 65.3% of students either agreed
or strongly agreed that TDD increased their confidence in the correctness of their code.
- 67.3% either agreed or strongly agreed that TDD increased their confidence
when making changes to their code base.
- Test completeness was 93.6% for
TDD; 90.0% for non-TDD.
Of course, there is the overhead of writing the tests and understanding how to use a unit testing framework. For smaller projects, this might be an excessive overhead, but for most non-trivial projects, test-driven development can still be useful. If you're only developing a few functions, you might only need a few tests, and it's great preparation for industry, where TDD is very common.
So, in short, don't just stress the importance of testing and hope they listen, integrate it into your teaching. If writing good tests is the norm in your class, it's far more likely that rigorous tests will be written.