How do you know what to test when writing unit tests?

Mike Roosa picture Mike Roosa · Sep 15, 2008 · Viewed 84.5k times · Source

Using C#, I need a class called User that has a username, password, active flag, first name, last name, full name, etc.

There should be methods to authenticate and save a user. Do I just write a test for the methods? And do I even need to worry about testing the properties since they are .Net's getter and setters?

Answer

Rob Cooper picture Rob Cooper · Sep 15, 2008

Many great responses to this are also on my question: "Beginning TDD - Challenges? Solutions? Recommendations?"

May I also recommend taking a look at my blog post (which was partly inspired by my question), I have got some good feedback on that. Namely:

I Don’t Know Where to Start?

  • Start afresh. Only think about writing tests when you are writing new code. This can be re-working of old code, or a completely new feature.
  • Start simple. Don’t go running off and trying to get your head round a testing framework as well as being TDD-esque. Debug.Assert works fine. Use it as a starting point. It doesn’t mess with your project or create dependencies.
  • Start positive. You are trying to improve your craft, feel good about it. I have seen plenty of developers out there that are happy to stagnate and not try new things to better themselves. You are doing the right thing, remember this and it will help stop you from giving up.
  • Start ready for a challenge. It is quite hard to start getting into testing. Expect a challenge, but remember – challenges can be overcome.

Only Test For What You Expect

I had real problems when I first started because I was constantly sat there trying to figure out every possible problem that could occur and then trying to test for it and fix. This is a quick way to a headache. Testing should be a real YAGNI process. If you know there is a problem, then write a test for it. Otherwise, don’t bother.

Only Test One Thing

Each test case should only ever test one thing. If you ever find yourself putting “and” in the test case name, you’re doing something wrong.

I hope this means we can move on from "getters and setters" :)