如何正确地对我的方法进行测试?
时间:2024-02-16
浏览:327
作者:佚名
有志者,事竟成!如果你在学习Golang,那么本文《如何正确地对我的方法进行测试?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
我编写此代码是出于教育目的,现在我需要为其编写一些测试。 首先,我需要测试 worker 方法,但我不明白如何正确执行? 我对于测试和 go 来说都是全新的。
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 现在这个测试不起作用,它可能因为工作方法中的无限循环而被卡住。然后我需要检查方法是否从队列中获取消息并将其传递给下载方法。
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 附带了一个相当广泛的内置测试库。查看https://pkg.go.dev/testing
我建议您查看以下教程:
- https://go.dev/blog/cover
- https://blog.alexellis.io/golang-writing-unit-tests/
- https://dev.to/quii/learn-go-by-writing-tests-structs-methods-interfaces--table-driven-tests-1p01
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
