DEV Community

Victor Basumatary
Victor Basumatary

Posted on

Why Do You Write Tests?

Testing has pros and cons (what doesn't?) and it only makes sense to do things when their benefits outweigh the costs. Usually at least. I hope I am speaking for most people here.

Anyway why do I write tests? I write it because it makes a nice todolist. Yeah it gives you that confidence that your program works correctly (does it though?) and refactoring becomes a cinch (I totally remember what ThisClassIMade20DaysAgo does) but I do it for the todolist because I'm forgetful.

Usually before I'm writing the code I imagine writing the code and a lot of times while imagining all of this I come across these edge cases. I obviously don't want to forget them so I write the tests for them. Or at least make empty tests with a descriptive enough name and comments.

So why do you write tests?

Top comments (2)

Collapse
 
eldadru profile image
Eldad Rudich

For many reasons

  1. Tests catch bugs: when strategically testing business logic, your test will eventually catch real issues and will save you time and money.
  2. Tests make you write better code: writing tests makes you write testable code - which means - smaller methods, smaller building blogs, DI, simpler code, etc'
  3. Tests make you think about edge cases: when writing tests to your code, you really have to go over the method/class logic and understand what cases are possible and need verification - this way you find new ways your code might fail and have to address that.
  4. Tests allow you/your peers to refactor the code freely: having tests that continuously check your code, allows you to freely change, add or improve the code without the fear of breaking something. without tests, nobody will have the courage to change the code which will eventually become rot.
  5. Tests are live code documentation: tests demonstrate how the code writer planned to use the code, many times with real examples the reader can adopt.

I guess I missed some reasons but those are my top.

Collapse
 
vlence profile image
Victor Basumatary

Also, as a side note, when I first started writing tests I wrote tests for the sake of writing tests. I don't know, you just feel better than everyone else. But then I stopped because my fingers started to hurt and it was just tiring really. Point I want to make is that now if I write tests it's just to be sure that my program does what it's supposed to do. I don't care so much if an individual function or class does something wonky as long as the program overall behaves correctly. I think it's impossible to have a misbehaving function or class in a correct program but I haven't really written that many programs anyway.