6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GoでTestifyでテストする際のassertとrequireの違い

Posted at

assertrequireか。

どちらも同じに見えるが、動きが少し異なる。

結論から言うと、

  • assertは途中でFailしてもテストは続行するが、
  • requireは途中でFailしたらそこでテスト関数を抜ける

requireは、テストに必要な前提条件などの確認で使い、
assertは目的のテストのために使うとよさそう。

使い分けの例:

Foo()をテストしたいが、Foo()を実行するためにフォルダが必要な場合。

func TestFoo(t *testing.T) {
  err := mkFooDir()
  require.NoError(t, err)

  actual := Foo()
  assert.Equal(t, fooExpected(), actual) 
}

サンプルコード

package main

import (
    "testing"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

func TestFoo(t *testing.T) {
    assert.Equal(t, 123, 123) // pass
    assert.Equal(t, 123, 321) // fail
    assert.Fail(t, "failed")  // fail

}

func TestBar(t *testing.T) {
    require.Equal(t, 123, 123) // pass
    require.Equal(t, 123, 321) // fail, and finish testing
    require.Fail(t, "failed")  // will be skipped.

}

Output:

=== RUN   TestFoo
    prog.go:12: 
            Error Trace:    prog.go:12
            Error:          Not equal: 
                            expected: 123
                            actual  : 321
            Test:           TestFoo
    prog.go:13: 
            Error Trace:    prog.go:13
            Error:          failed
            Test:           TestFoo
--- FAIL: TestFoo (0.00s)
=== RUN   TestBar
    prog.go:19: 
            Error Trace:    prog.go:19
            Error:          Not equal: 
                            expected: 123
                            actual  : 321
            Test:           TestBar
--- FAIL: TestBar (0.00s)
FAIL

参考URL:
https://www.yellowduck.be/posts/assert-vs-require-in-testify/

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?