我为教育目的编写了这段代码,现在我需要为它编写一些测试. 首先,我需要测试方法工作者,但我不明白如何才能正确地进行测试? 我对测试和大体来说都是全新的.

package worker

import (
    "context"
    "fmt"
)

type Queue interface {
    TakeMessage() (<-chan string, error)
}

type Download interface {
    Download(url string) error
}

type Worker struct {
    queue    Queue
    download Download
}

func NewWorker(queue Queue, download Download) *Worker {
    newWorker := Worker{}
    newWorker.queue = queue
    newWorker.download = download

    return &newWorker
}

func (w *Worker) Worker(ctx context.Context) error {
    msgs, err := w.queue.TakeMessage()
    if err != nil {
        return fmt.Errorf("error while consume queue: %w", err)
    }
    for {
        select {
        case <-ctx.Done():
            return nil
        case msg := <-msgs:
            fmt.Println(msg)
            w.download.Download(msg)
        }
    }
}

我编写了几行测试代码,并假设在将ctx.Done()传递给通道时判断Worker是否返回nil.现在这个测试不起作用,可能是因为Worker方法中的无限循环而停滞.然后,我需要判断方法是否从队列中获取消息并将其传递给Download方法.

package worker

import (
    "context"
    "errors"
    "testing"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/mock"
)

type MockQueue struct {
    mock.Mock
}

type MockDownloader struct {
    mock.Mock
}


func (m *MockQueue) TakeMessage() (<-chan string, error) {
    strCh := make(chan string)
    strCh <- "some_url/some.txt"
    return strCh, nil
}


func (d *MockDownloader) Download(url string) error {
    if url == "some_url/some.txt" {
        return nil
    } else {
        return errors.New(url)
    }
}


func TestWorkerCloseContext(t *testing.T) {
    ctx, cancel := context.WithCancel(context.Background())
    resultCh := make(chan error)
    newQueue := &MockQueue{}
    newDownload := &MockDownloader{}
    newWorker := Worker{newQueue, newDownload}
    go func() {
        resultCh <- newWorker.Worker(ctx)
    }()
    cancel()
    assert.Nil(t, <-resultCh)
}

func TestWorkerMessageReceive(t \*testing.T) {
   ctx, cancel := context.WithCancel(context.Background())
   resultCh := make(chan error)
   newQueue := &MockQueue{}
   newDownload := &MockDownloader{}
   newWorker := Worker{newQueue, newDownload}
   go func() {
       resultCh \<- newWorker.Worker(ctx)
    }()
   //some code here
}

Go相关问答推荐

Go Fiber和HTMX—HX—Trigger header被更改为HX—Trigger,这不是HTMX监听的内容

你能帮我优化一个golang代码关于函数CrossPointTwoRect

GetSecretValue,get identity:get credentials:无法刷新缓存的凭据

GORM Find(&;Room)操作使用空数据而不是实际数据填充 struct

如何在gofr发起的服务间调用请求中添加Authorization Header?

Golang中的泛型 struct /接口列表

通过渠道和goroutines增值1000倍

Go:为什么我不能比较 net.Addr

未实现的 desc = 未知服务 pb.AuthService 我的简单身份验证服务器上出现错误

Go 中如何判断 struct 体是否包含另一个 struct 体?

在golang中以JSON格式获取xwwwformurlencoded请求的嵌套键值对

带有前导零的整数参数被 flag.IntVar 解析为八进制

xml.Unmarshal 不支持的类型 struct

更改多对多连接表的名称

如何在 `hashicorp / terraform-exec` 中将 `ApplyConfig` 传递给 `tf.Apply()`?

闭包所处的环境范围是什么?

Apache Beam 在 Go 中从 PCollection 中 Select 前 N 行

Go 泛型:自引用接口约束

使用go doc命令查看示例函数?

在 Go 中表达函数的更好方法( struct 方法)