0
测试中,我有一个简单的去功能我想测试:“无效的内存地址”,而在围棋
func root(c echo.Context) error {
return c.String(http.StatusOK, "This is the root!")
}
我的测试是这样的:
import (
"net/http"
"testing"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
type Context struct {
echo.Context
}
func TestRoot(t *testing.T) {
c := new(Context)
expectedResult := c.String(http.StatusOK, "This is the root!")
actualResult := c.String(http.StatusOK, "This is the root!")
assert.Equal(t, expectedResult, actualResult, "they should be equal")
}
现在,当我运行测试,我得到这个错误:
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
我是相当新的去,只是想试图理解它。我知道,当我处理一个不存在的对象时,我得到这个错误。但是我所做的每个变量赋值都没有变化,为nil
。
Can somebody point me to a solution? Or tell me how simple unit tests should look like in Go?
你的'Context'类型具有嵌入式接口; 'echo.Context',它需要一个值。我不确定你在这里准备做什么,因为你没有处理任何请求或响应。 – JimB
在调用该接口上的方法之前,'TestRoot'函数必须将c.Context设置为非零接口值。也许Echo包提供了一种创建测试环境的方法。 –
这是我的问题。在我习惯的单元测试中,我只测试根函数是否以合适的值返回正确的对象。我怎么能这样做在Go(或者我不应该这样做呢?) –