我有一种用于重复身份验证的类型:type Authorizer struct { requester *Requester closeChannel chan error}func (requester *Requester) Authorize(autoClose bool) { // Create a new authorizer from the requester and the close-channel authorizer := Authorizer{ requester: requester, closeChannel: requester.closer, } // Ensure that the requester has a reference to the authorizer so we can access the // updated token requester.authorizer = &authorizer // Begin the authentication loop concurrently go authorizer.manageAuthorization()}func (authorizer *Authorizer) manageAuthorization() { for { select { case _, ok := <-authorizer.closeChannel: if ok { fmt.Printf("Closed\n") return // NEVER RUNS } default: break } fmt.Printf("Not closed\n") // Do inner authorization logic }}此类创建身份验证器并处理请求:type Requester struct { authorizer *Authorizer client *http.Client closer chan error}func NewRequester() *Requester { requester := Requester{ client: new(http.Client), closer: make(chan error), } requester.Authorize(false) return &requester}func (requester *Requester) Close() { fmt.Printf("Closing...\n") close(requester.closer)}所以,到目前为止,我的测试都通过了这段代码。但是,我在进行报道时遇到了一个有趣的问题。考虑以下代码段:// Create the test clientclient := Requester{}client.closer = make(chan error)// Begin authenticationclient.Authorize(false)// Now, close the channelclose(client.closer)如果我将它嵌入到测试中并尝试使用它运行代码覆盖率,我注意到指示的行永远不会运行。此外,我在此处添加的调试消息显示如下:Not closedNot closedNot closedClosing...Not closedNot closedNot closed消息不会Closed打印。那么,我在这里做错了什么?
1 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
ok将false在通道关闭时。尝试
case _, ok := <-authorizer.closeChannel:
if !ok {
return // RUNS
}
- 1 回答
- 0 关注
- 98 浏览
添加回答
举报
0/150
提交
取消