如何测试结构是否实现了特定接口

时间:2019-10-02 17:59:45

标签: go ginkgo gomega

编写后续测试的正确方法是什么?

为避免在程序包内部编写

var _ Common = (*Stuff)(nil), 
var _ Common2 = (*Stuff)(nil)
var _ Common3 = (*Stuff)(nil)
...

``

包装材料

  

stuff / common.go

package stuff

type Common interface {
  String() string
}
  

stuff / common2.go

package stuff

type Common2 interface {
  String2() string
}
  

stuff / stuff_suite_test.go

package stuff

import (
  "testing"
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)

func Test(t *testing.T) {
  RegisterFailHandler(Fail)
  RunSpecs(t, "Stuff")
}
  

stuff / stuff_test.go

package stuff

import (
  "testing"
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
}

var _ = Describe("Stuff", func() {
  It("implements Common", func() {
    var s interface{} = &Stuff{}
    _, ok := s.(Common)
    Expect(ok).To(Equal(true))
  })
})

It("implements Common 2", func() {
  var _ Common2 = (*Stuff)(nil) // ok
})
  

stuff / stuff.go

package stuff

type Stuff struct {}

func (s *Stuff) String() string {
  return ""
}

软件包lib

  

/lib/lib.go

import "stuff"

func GetCommon() *stuff.Stuff {
  return &stuff.Stuff{}
}
  

/lib/lib_suite_test.go

package lib

import (
  "testing"
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)

func Test(t *testing.T) {
  RegisterFailHandler(Fail)
  RunSpecs(t, "Lib")
}
  

/lib/lib_test.go

package lib

import (
    . "github.com/onsi/ginkgo"
    . "github.com/onsi/gomega"
)

var _ = Describe("Lib", func() {
  It("can be created", func() {
    l := GetCommon()
    Expect(l).NotTo(BeNil())
  })
}

0 个答案:

没有答案