2016-10-07 28 views
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?

+0

你的'Context'类型具有嵌入式接口; 'echo.Context',它需要一个值。我不确定你在这里准备做什么,因为你没有处理任何请求或响应。 – JimB

+0

在调用该接口上的方法之前,'TestRoot'函数必须将c.Context设置为非零接口值。也许Echo包提供了一种创建测试环境的方法。 –

+0

这是我的问题。在我习惯的单元测试中,我只测试根函数是否以合适的值返回正确的对象。我怎么能这样做在Go(或者我不应该这样做呢?) –

回答

-1
package main 

import (
    "testing" 

    "github.com/labstack/echo" 
) 

// Context context struct 
type Context struct { 
    echo.Context 
} 

// TestRoot func test root 
func TestRoot(t *testing.T) { 
    c := &Context{} 

    if c == nil { 
     t.Errorf("ERROR: type Context could not be null, received %v", c) 
    } 
} 

你恐慌的错误玉米消失,告诉我,如果我错了。

我不明白你想要做什么。但我只是试图解决你的恐慌错误,并告诉你如何进行测试,你只需要使用你的函数并测试一些条件的结果,然后使用测试包来测试错误