我有一种用于重复身份验证的类型:
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 client
client := Requester{}
client.closer = make(chan error)
// Begin authentication
client.Authorize(false)
// Now, close the channel
close(client.closer)
如果我将它嵌入到测试中并尝试使用它运行代码覆盖率,我注意到指示的行永远不会运行。此外,我在此处添加的调试消息显示如下:
Not closed
Not closed
Not closed
Closing...
Not closed
Not closed
Not closed
消息不会Closed打印。那么,我在这里做错了什么?
慕姐8265434
相关分类