DEV Community

Discussion on: How to write testable code

Collapse
 
gypsydave5 profile image
David Wickes

Good article - thanks for sharing it!

Although this class works it is impossible to unit test due to two different dependencies being instantiated rather than injected.

This is a great way to spot tightly coupled code that is just aching for a bit of DI. If you can see an object getting newed up inside a method... inject it instead! πŸ’―

First of all we use Mockery to mock our account class.

I tend to eschew the use of mocking libraries and just roll my own test doubles. It stops people arguing with me about which one to use... 🀣

How to write testable code

Of course, the best way to write testable code - to absolutely guarantee that it's testable - is to write the tests first. πŸ˜‰

Collapse
 
ddarrko profile image
Daniel

Glad you liked the post !

Yup - if I see β€˜new’ anywhere in a PR you can bet I’ll be investigating to see if it should be refactored (it almost always should)

Maybe I’ll do a TDD one in the future :)