1、接着,更新 count() 函数以接受另一个参数 countBytes 。当这个输入参数设置为 true 时,函数应该统计字节数。(提示:查看 Go 文档中 bufio.Scanner 类型的所有可用方法。)
以下是更新后的 count() 函数代码:
func count(r io.Reader, countLines bool, countBytes bool) int {
scanner := bufio.NewScanner(r)
if countBytes {
scanner.Split(bufio.ScanBytes)
} else if !countLines {
scanner.Split(bufio.ScanWords)
}
wc := 0
for scanner.Scan() {
wc++
}
return wc
}
上述代码中, count() 函数新增了 countBytes 参数。当 countBytes 为 true 时, scanner.Split() 方法会将扫描器的分割类型设置为按字节分割,从而实现字节数的统计。当 countBytes 为 false 且 countLines 为 false 时,扫描器按单词分割;若 countLines 为 true ,扫描器使用默认的按行分割方式。最后,通过循环调用 scanner.Scan() 方法并递增计数器 wc 来统计相应的数量。
2、编写测试以确保新功能按预期工作。
可以采用不同方法来编写测试确保新功能按预期工作,以下是不同场景下的测试编写方式:
1. 对于todo列表功能:
- 首先在代码中添加所需外部库的导入部分,示例如下:
```go
import (
"io/ioutil"
"os"
"testing"
"pragprog.com/rggo/interacting/todo"
)
```
- 接着创建测试用例,如测试添加任务功能:
```go
// TestAdd tests the Add method of the List type
func TestAdd(t *testing.T) {
l := todo.List{}
taskName := "New Task"
l.Add(taskName)
if l[0].Task != taskName {
t.Errorf("Expected %q, got %q instead.", taskName, l[0].Task)
}
}
```
- 再添加测试来验证完成任务方法:
```go
// TestComplete tests the Complete method of the List type
func TestComplete(t *testing.T) {
l := todo.List{}
taskName := "New Task"
l.Add(taskName)
if l[0].Task != taskName {
t.Errorf("Expected %q, got %q instead.", taskName, l[0].Task)
}
if l[0].Done {
t.Errorf("New task should not be completed.")
}
l.Complete(1)
if !l[0].Done {
t.Errorf("New task should be completed.")
}
}
```
2. 对于使用表驱动测试的情况:
- 创建一个新文件,如`actions_test.go`,添加包定义和导入语句:
```go
package main
import (
"os"
"testing"
)
```
- 创建测试函数来测试`filterOut()`函数,并添加匿名结构体切片定义测试用例:
```go
func TestFilterOut(t *testing.T) {
testCases := []struct {
name string
file string
ext string
minSize int64
expected bool
}{
// 这里可以添加具体的测试用例数据
}
}
```
3. 对于CLI工具:
- 在`main_test.go`文件中定义包名并导入所需包,如`fmt`、`os`、`os/exec`、`filepath`等。
- 利用`TestMain()`函数进行额外的测试设置,该函数有助于控制测试所需资源的设置和清理。
- 主要目标是使用`go build`工具将程序编译成二进制文件,并使用不同参数执行二进制文件,断言其行为是否正确。


816

被折叠的 条评论
为什么被折叠?



