Go test function with pointer reference

时间:2018-06-04 16:51:20

标签: go

I'm working on unit tests on a Go project, and I'm new to Go. So to start I wanted to test something easy. And I started with this function:

func (this *Service) InList(idPerson string, personsId []string) bool {
    for _, personsId := range personsId {
        if id == idPerson {
            return true
        }
    }

    return false
}

Service is a struct defined on top of the class.

This is the test I wrote:

func TestValidatePersonID(t *testing.T) {
   personID := "12345"

   personIDs := []string{"12345", "123456t", "1234567a"}

   ok := *Service.InList(personID, personIDs)

   if !ok {
      t.Errorf("Id %v not found", personID)
   }
}

If i try to Call Service without * I get the error:

invalid method expresion (needs pointer reciever)

If i try to call the function (*Service).inList, it says I'm missing an argument. I'm new to Go if anyone could point to me what I'm doing wrong and how Could I get a pointer receiver of that Service in my test?. I would appreciatte it.

3 个答案:

答案 0 :(得分:2)

The correct syntax for the method expression is:

ok := (*Service).InList(nil, personID, personIDs)

This snippet adds nil as the receiver argument and uses parentheses to specify the type correctly.

The approached used in the question is not idiomatic. Either call a method on a value

s := Service{}
ok := s.InList(personID, personIDs)

or convert the method to a function.

答案 1 :(得分:1)

You have to call a method on an instance of its receiver type. So, for a method defined on *Service, you must call it on an instance of *Service:

var foo *Service
foo = &Service{}
foo.InList(personID, personIDs)

However, in your case, there's no reason for this to be a method; it doesn't seem to have anything at all to do with its receiver (it never references it), so it could just be a regular function. Also note that it's unidiomatic to name the receiver this in Go.

I also highly recommend at least taking the Go tour, which covers writing methods in detail, with interactive examples.

答案 2 :(得分:0)

如果你没有引用接收者对象,那么你就不应该有一个,尽可能保持你的代码。

编写方法或函数有三种方法,每种方法都有自己的用途。

  1. 没有接收器,当函数中没有引用接收器时(我们称之为函数)
  2. 一个值接收器,接收器被引用,但在方法中没有改变(我们称之为方法)
  3. 指针接收器,接收器中的某些东西将在方法中被改变