<p>I am building some package that relies, at least for some functionality, on an external api which is not mine, and as such might change or stop working at any moment. </p>
<p>To isolate the api code for this external service as much as possible from the rest from my code I put all this code in a sub package that satisfies an interface I declared in the root of my package to access it.</p>
<p>Then I declare some tests in that sub package that do some calls of which I know what the output should be and compare that with what it should be. This way any changes to the api that I am not aware of might be caught.</p>
<p>Is it idiomatic to use tests like this? It seems a bit weird since your tests can fail now because your internet connection might be down or the request times out for some other reason.</p>
<hr/>**评论:**<br/><br/>DenzelM: <pre><p>Some people refer to what you're talking about as broad integration tests or system tests. These are completely normal. They'll help you catch the exact issue you're worried about: "changes to the API you're not aware of".</p>
<p>With that said, you'll want to use <a href="https://stackoverflow.com/questions/25965584/separating-unit-tests-and-integration-tests-in-go" rel="nofollow">build tags</a> to separate your deterministic tests from your nondeterministic ones.</p></pre>diabetesjones: <pre><p>Good question, I think there are a lot of different approaches. I make dummy API accounts, get the secrets from environment variables, and put the API calls right into my tests. I assume I will have an internet connection - I need this for so much else in my workflow that this is a safe assumption. Then I can make API calls on this dummy account without screwing up my real dev/staging/prod API creds. Just <code>export</code> your necessary env vars before tests. </p>
<p>Like this:<br/>
<a href="https://github.com/etherparty/coinpayments/blob/develop/client_test.go" rel="nofollow">https://github.com/etherparty/coinpayments/blob/develop/client_test.go</a><br/>
Then a test using that client:<br/>
<a href="https://github.com/etherparty/coinpayments/blob/develop/tx_test.go" rel="nofollow">https://github.com/etherparty/coinpayments/blob/develop/tx_test.go</a></p></pre>
Do you use tests for external (rest) apis you rely on? And what do you test if you do?
blov · · 1429 次点击这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传