2017-09-02 112 views
0

对我来说,能够断言我的测试中调用了多少次假/嘲笑方法是非常重要的,我想知道在不使用诸如testify之类的情况下做到这一点的最佳方法是什么。就我而言,对模拟方法的调用是一些递归调用的结果。assert_called_once()或assert_called_xyz()....相当于?

可以说我有各种动物的表驱动测试,我想断言你好实际上是要求一些测试,但不是为其他人。在某些情况下,对于给定的测试,应该多次调用它(迭代切片)。

添加一个计数器并在我的表驱动测试中作出断言是否合适?在我看来,也许有更好的方法来做到这一点。

如果我的确向hello方法中添加了一个计数器,那么应​​该在哪里处理并检查它。在假方法本身或在测试等?

type fakeFarmService struct { 
 
\t abc.someFarmServiceInterface 
 
} 
 

 
func (f *fakeFarmService) Hello(ctx context.Context, in *abc.FarmRequest) (*abc.FarmResponse, error) { 
 
\t if in.GetAnimal() == Monkey { 
 
\t \t return &abc.HelloResponse{}, nil 
 
\t } 
 
\t return nil, errors.New("an error") 
 
}

回答

1

我已经用在结构计数器的方法,然后断言它的封装级单元测试中多次过去。尽管如此,它可能只是在包装级别之前,当你想要测试这样的内部断言时。我相信这是Go的一个可接受的方式。如果您决定使用全局变量或同时运行测试,那么要小心正确地同步对计数器的访问。

package main 

import (
    "fmt" 
    "sync" 
    "testing" 
) 

type fakeable interface { 
    Hello() 
} 

type fakeFarmService struct { 
    mu  sync.Mutex 
    counter int 
} 

func (f *fakeFarmService) Hello() { 
    f.mu.Lock() 
    f.counter++ 
    f.mu.Unlock() 
} 

func helloCaller(callee fakeable) { 
    callee.Hello() 
} 

func TestCallingTheHello(t *testing.T) { 
    fakeSvc := &fakeFarmService{} 
    helloCaller(fakeSvc) 
    helloCaller(fakeSvc) 

    // we expect that Hello method of fakeable was called 2 times 
    fakeSvc.mu.Lock() 
    defer fakeSvc.mu.Unlock() 
    if c := fakeSvc.counter; c != 2 { 
     t.Errorf("unexpected call count, want 2, got %d", c) 
    } 
} 

func main() { 
    TestCallingTheHello(&testing.T{}) 
} 

https://play.golang.org/p/RXKuLKIZwc围棋

  1. Testing Techniques by Andrew Gerrand
  2. NewStore TechTalk - Advanced Testing with Go by Mitchell Hashimoto
(测试误差不会操场内工作)

一些好的材料上先进的检测