How to run all test cases even if one test case fails

huangapple go评论113阅读模式
英文:

How to run all test cases even if one test case fails

问题

  1. func Test_something(t *testing.T) {
  2. // 测试用例1:传递一个数组
  3. // 这里是一些逻辑
  4. // 测试用例2:传递一个空数组 --> 这将导致测试失败
  5. // 这里是一些逻辑
  6. // 测试用例3:传递其他内容
  7. // 这里是一些逻辑
  8. }

我正在编写一些单元测试,但我不确定是否可以运行一个名为Test_something的测试,其中包含多个测试用例,而不会在一个失败后停止执行其他测试用例。这样做是否有意义?

在控制台上,我希望看到类似于以下内容:

  1. TESTCASE1: SUCCESS <message>
  2. TESTCASE2: FAIL <message>
  3. TESTCASE3: SUCCESS <message>

目前,我得到的结果类似于:

  1. TESTCASE1: SUCCESS <message>
  2. TESTCASE2: FAIL <message>

它会在TESTCASE2失败后自然停止执行。

英文:
  1. func Test_something(t *testing.T) {
  2. // TEST CASE1: pass an array
  3. // some logic here
  4. // TEST CASE2: pass an EMPTY array --&gt; this will cause test to fail
  5. // some logic here
  6. // TEST CASE3: pass something else
  7. // some logic here

I am writing some unit tests but I am not sure if it's possible to run a test Test_something that has several test cases without stopping the execution of other test cases if one fails. Or does it even make sense?

In console I would like to see something like this.

  1. TESTCASE1: SUCCESS &lt;message&gt;
  2. TESTCASE2: FAIL &lt;message&gt;
  3. TESTCASE3: SUCCESS &lt;message&gt;

At the moment I get something like this:

  1. TESTCASE1: SUCCESS &lt;message&gt;
  2. TESTCASE2: FAIL &lt;message&gt;

It will naturally stop executing after TESTCASE2 fails.

答案1

得分: 1

使用 t *testing.T,你可以调用以下函数:

  • t.Errorf(...): 它不会停止后续的测试。
  • t.Fatalf(...): 它会停止后续的测试。

详细信息请参考官方文档

英文:

with t *testing.T you may call:

  • t.Errorf(...): it will not stop next tests.
  • t.Fatalf(...): it will stop next tests.

See official doc.

答案2

得分: 1

你可以使用testing.T.Run函数来使用子测试。它允许将多个测试用例组合在一起,并为每个测试用例分别设置状态。

  1. func TestSomething(t *testing.T) {
  2. t.Run("第一个测试用例", func(t *testing.T) {
  3. // 在这里实现你的第一个测试用例
  4. })
  5. t.Run("第二个测试用例", func(t *testing.T) {
  6. // 在这里实现你的第二个测试用例
  7. })
  8. }
英文:

You can use subtest with the help of the testing.T.Run function. It allows to gather several test cases together and have separate status for each of them.

  1. func TestSomething(t *testing.T) {
  2. t.Run(&quot;first test case&quot;, func(t *testing.T) {
  3. // implement your first test case here
  4. })
  5. t.Run(&quot;second test case&quot;, func(t *testing.T) {
  6. // implement your second test case here
  7. }
  8. }

huangapple
  • 本文由 发表于 2022年7月19日 18:53:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/73035613.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定