In our last post we wrote a simple set of bindings for libspotify in Go. By the end of the post we had an example compiling, but we had a bad API key for our spotify application. One obvious way to recify this would be to grab an API key if you are a Spotfy Premium user. Another workaround is to use a mock library to make sure the code is working the way we want. We will link this mock library with Build tags.
Start by installing libmockspotify:
1 2 3 4 5 6
Once libmockspotify is installed, we can link to that instead of the real libspotify:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
The following code should output:
Using build tags
It’s great that we have libmockspotify for testing purposes, but it doesn’t make sense to always mock spotify in our project. This is where Build Tags come into play. We can use build tags to conditionally choose which library to link to.
Let’s link both libspotify and libmockspotify in our file:
1 2 3 4 5
This approach obviously will not work as is, so we will instead link each library conditionally based on the mock build take that we will define:
1 2 3 4 5
This will link libmockspotify when the mock build tag is defined, otherwise we will use the real libspotify. So then how do we define build tags? Simple:
Thats enough for today, have fun with build tags! I will leave you with one more pro tip!
~/.vim folder I have a ftplugin for Go that includes a binding for running tests:
You see how I include the test tag in all of my test running? This makes it convenient when linking mock libraries specific for running tests!
Until next time!