<p>Hi there, I'm currently trying to write tests for my very simple microservice. I'm using httprouter and I've tried to use the answers from this question: <a href="https://stackoverflow.com/questions/43502432/how-to-write-test-with-httprouter" rel="nofollow">https://stackoverflow.com/questions/43502432/how-to-write-test-with-httprouter</a> but I just get a runtime error or the parameters don't seem to get passed through to the function. </p>
<p>My test file is here on Github: <a href="https://github.com/AndrewRMorgan/url-shortener/blob/master/main_test.go" rel="nofollow">https://github.com/AndrewRMorgan/url-shortener/blob/master/main_test.go</a></p>
<p>Any help would be greatly appreciated.</p>
<hr/>**评论:**<br/><br/>epiris: <pre><p>In case you are curious why no one answered, you failed to provide the two most important things. The error and the code from the offending frame within the stack trace. I assume you omitted them because you felt it was not related, but until you are familiar enough with a language (this applies to all languages, not just Go) to no longer get stuck on these sort of problems than you are not familiar enough to omit details. Just friendly advice for getting help and avoiding frustrating XY problem dialogs. If you are still stuck post a runnable example and I'll tell you what is wrong.</p></pre>qu33ksilver: <pre><p>What is the error you are getting and at which line no. ? You have to be a bit more specific.</p></pre>sethammons: <pre><p>I avoid httprouter because of its non-conformity to the stdlib. If I go with a non-stdlib router these days, I use chi.</p>
<p>As for testing, what I've done in the past is something like:</p>
<pre><code>e := someStructWithAnHandlerFunction{}
rw := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/blah", nil)
params := httprouter.Params{}
params = append(params, httprouter.Param{Key: "token", Value: "my token value"})
// GetSomeEndpoint is the handler function under test
e.GetSomeEndpoint(rw, r, params)
// response
if got, want := rw.Code, http.StatusOk; got != want {
t.Errorf("got %d, want %d", got, want)
}
</code></pre>
<p>Edit: formatting</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传