It can be tough to get anywhere close to 100% code coverage when funcs in the “stdlib” can’t be forced to error. This post takes you through several of the common funcs built in to golang and shows you how to trigger an error to help you bump up your code coverage. This list is short and skews heavily toward http, where I spend most of my time.
We can pass an invalid port number to trip up ListenAndServe(). Full working example this time since this won’t run in the playground.
If choosing the port is not an option, we can cheat on our unit test, and block that port on the host. However, the stdlib doesn’t support this in any form, so you’d have to pick a stoppable http server like tylerb/graceful, like so:
Often, you want a way to force a connection error to simulate problems with some API you’re consuming as part of your service. Golang’s stdlib provides the RoundTripper interface to allow us to customize interaction with the network.
If you run into a golang func that you can’t break, post it in the comments here or tweet it to me.