微软单元测试.是否可以跳过测试方法体的测试?

Dru*_*der 27 c# unit-testing mstest

所以我有需要从测试方法体跳过当前测试的情况.最简单的方法是在测试方法中写这样的东西.

if (something) return;
Run Code Online (Sandbox Code Playgroud)

但是我有很多复杂的测试,我需要一种方法来跳过我在当前测试方法体中调用的方法的测试.可能吗?

Ser*_*kiy 64

你不应该以这种方式跳过测试.最好做以下事情之一:

  • 将测试标记为通过[Ignore]属性忽略
  • NotImplementedException从测试中抛出
  • Assert.Fail()(否则你可以忘记完成这个测试)
  • 删除此测试

还要记住,您的测试不应包含条件逻辑.相反,您应该创建两个测试 - 为每个代码路径单独测试(使用名称,描述您正在测试的条件).所以,而不是写:

[TestMethod]
public void TestFooBar()
{
   // Assert foo
   if (!bar)
      return;
   // Assert bar
}
Run Code Online (Sandbox Code Playgroud)

写两个测试:

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

[Ignore] // you can ignore this test
[TestMethod]
public void TestBar()
{
   // set bar == true
   // Assert bar
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*zey 44

继其他答案(和建议):我建议使用Assert.InconclusiveAssert.Fail,因为原来的海报的情况是不明确的失败案例.

使用Inconclusive结果清楚地表明,你不知道这个测试是成功还是失败-这是一个重要的区别.没有证明成功并不总是构成失败!

  • 许多年后,MSTest - > TFS最终将Assert.Inconclusive识别为"其他"而不是"失败".有关详细信息,请参阅https://github.com/Microsoft/vstest/issues/525,如果这对您来说和我一样重要:-). (2认同)

小智 12

您可以忽略测试并在代码中完全不受影响.

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

}
Run Code Online (Sandbox Code Playgroud)

  • 只是为了简洁:[TestMethod,Ignore] (4认同)
  • 我认为他的意思是从测试中以编程方式决定这一点,类似于NUnit的Assume. (3认同)