我有一種用于重復身份驗證的類型: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 關注
- 115 瀏覽
添加回答
舉報
0/150
提交
取消