43

そのため、テストメソッド本体から現在のテストをスキップする必要がある状況があります。最も簡単な方法は、テストメソッドでこのようなものを書くことです。

if (something) return;

しかし、私には非常に複雑なテストがあり、現在のテストメソッド本体で呼び出すメソッドからテストをスキップする方法が必要です。出来ますか?

4

4 に答える 4

93

You should not skip test this way. Better do one of following things:

  • mark test as ignored via [Ignore] attribute
  • throw NotImplementedException from your test
  • write Assert.Fail() (otherwise you can forget to complete this test)
  • remove this test

Also keep in mind, that your tests should not contain conditional logic. Instead you should create two tests - separate test for each code path (with name, which describes what conditions you are testing). So, instead of writing:

[TestMethod]
public void TestFooBar()
{
   // Assert foo
   if (!bar)
      return;
   // Assert bar
}

Write two tests:

[TestMethod]
public void TestFoo()
{
   // set bar == false
   // Assert foo
}

[Ignore] // you can ignore this test
[TestMethod]
public void TestBar()
{
   // set bar == true
   // Assert bar
}
于 2012-07-25T12:58:36.193 に答える
59

Further to other answers (and as suggested): I'd suggest using Assert.Inconclusive over Assert.Fail, since the original poster's situation is not an explicit failure case.

Using Inconclusive as a result makes it clear that you don't know whether the test succeeded or failed - which is an important distinction. Not proving success doesn't always constitute failure!

于 2012-07-25T13:24:45.053 に答える
17

You can ignore a test and leave it completely untouched in the code.

[TestMethod()]
[Ignore()]    //ignores the test below
public void SomeTestCodeTest()
{
   //test code here

}
于 2012-07-25T13:04:02.327 に答える
1

There is an Assert.Inconclusive() method which you can use to nicely skip the current test. Check the docs. Basically it will throw an exception and will show this method as Skipped.

I used this as a programmatic check in my code inside the test method:

if (!IsEnvironmentConfigured())
{
   Assert.Inconclusive("Some message");
}

Here is the result:

! ShouldTestThisMethod [31ms]

Test Run Successful.
Total tests: 92
     Passed: 91
    Skipped: 1
 Total time: 1.2518 Seconds
于 2020-05-04T23:22:14.207 に答える