DEV Community

Discussion on: Writing 'Testable' Code Feels Wrong

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Testable using automated test frameworks

Collapse
 
pentacular profile image
pentacular

That's not very meaningful. :)

A test is just a small application that does something and sees if it got what it expected.

Parts of your code that have no API will be hard to test -- you'll need to simulate a human user.
(But is this useful to you? Hard to know, since you won't talk about your testing requirements)

Parts of your code that have an API will be straight-forward to test -- you can just call them.

But sometimes code operates in a larger environment.
So testing writing to a database will require setting up a database to write to.

The usual approach here is to set up a virtual database of some kind -- perhaps a mock, fake, or light weight implementation.

If your API doesn't allow the caller to supply the databases they want to operate on, then you'll find testing those difficult.

(And for database, substitute any other kind of significant external resource).

And that's pretty much all there is to it.

If your code has APIs, and a way to supply external dependencies, it should be straight-forward to test.

But, again, you need to think about what kinds of tests are actually useful for your use-case.
Unit tests? Regression tests? Integration tests? End-to-end tests? QA tests? Monitoring?

Tests are a cost, so you should concentrate on tests with high utility, and minimize tests with low utility.

So you must actually think about what your testing requirements are, and what it will mean for your code to be testable.