dpg2905 2018-06-04 16:51
浏览 19
已采纳

使用指针参考进行测试功能

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条回答 默认 最新

  • dpwbc42604 2018-06-04 16:53
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用