loading...

Discussion on: No excuses, write unit tests

Collapse
chuckwoodraska profile image
Chuck Woodraska

I feel like a lot of my time is spent writing mock objects for DB data or other outside things. Any suggestions for writing tests that hit external sources.

Collapse
lietux profile image
Janne "Lietu" Enberg

You really don't say much that can be used to help you out with your specific use case, it depends heavily on what you're writing, what languages, frameworks and tools, etc. you are using.

However, some common solutions:

  • Fixtures: Record known good test data sets somewhere and reuse that in all your tests as much as possible

  • Automatic mocking: Many frameworks and languages provide powerful ways to (mostly) automatically mock certain kinds of things (e.g. standard HTTP requests, database access)

  • Spend some time improving your tools: If you constantly spend time mocking your DB layer, make your DB layer support mocking out of the box - e.g. define the mock class and fixture at the same time you create your model classes

  • Change tools: If your tools for some reason require an unreasonable effort to set up unit tests, maybe you should find better tools. Of course I'm not suggesting you just take your 5 year project and rewrite it from scratch, but you can start a process of migrating to a better framework/language/other tool progressively.

Generally when starting a new project I spend some time in making sure it's easy to work with, including to make unit tests.

Here's some resources for some languages I happen to have recent experience in testing:

Most languages and frameworks with any reasonable standing in the world will have ways to run unit tests, but sometimes it takes a bit extra effort to cater to your specific use-case.

Collapse
jackmarchant profile image
Jack Marchant Author

I would suggest that as a general rule you shouldn't be writing tests any more than 20-30% of the time while building a feature. If it's more than that I would question the architecture decisions in the app.
Sometimes you will have to write mocks but I find being strict about the interface to an external source is key!