我将在工作中开始一个新项目,并想进入单元测试。我们将使用Visual Studio 2008, c#和ASP。NET MVC之类的东西。我正在考虑使用NUnit或Visual Studio 2008的内置测试项目,但我也愿意研究其他建议。是一种系统比另一种更好,还是比另一种更容易使用/理解?

我希望让这个项目成为我们未来发展努力的“最佳实践”。


当前回答

MSTest is essentially NUnit slightly reworked, with a few new features (such as assembly setup and teardown, not just fixture and test level), and missing some of the best bits (such as the new 2.4 constraint syntax). NUnit is more mature, and there is more support for it from other vendors; and of course since it's always been free (whereas MSTest only made it into the Professional version of Visual Studio 2008, and before that it was in way more expensive SKUs), and most ALT.NET projects use it.

话虽如此,还是有一些公司非常不愿意使用没有微软标签的东西,尤其是OSS代码。因此,拥有官方的微软测试框架可能是这些公司需要进行测试的动机;老实说,重要的是测试,而不是你使用什么工具(使用Tuomas Hietanen的代码,你几乎可以让你的测试框架可互换)。

其他回答

我从MSTest开始,但我因为一个简单的原因而改变了。MSTest不支持从其他程序集继承测试方法。

我讨厌多次编写相同的测试。特别是在一个大型项目中,测试方法可以很容易地运行到100个测试。

NUnit正是我所需要的。NUnit唯一缺少的是Visual Studio插件,它可以显示每个测试的红色/绿色状态(就像VSTS一样)。

Visual Studio测试框架的一个小麻烦是,它会创建许多测试运行文件,这些文件往往会使您的项目目录变得混乱——尽管这并不是什么大问题。

另外,如果你缺少一个像TestDriven这样的插件。NET,你不能在Visual Studio环境中调试你的NUnit(或MbUnit, xUnit等)单元测试,而你可以在Microsoft Visual Studio测试框架中进行,这是内置的。

Daok列出了Visual Studio 2008测试项目的所有优点。下面是NUnit的优点。

NUnit has a mocking framework. NUnit can be run outside of the IDE. This can be useful if you want to run tests on a non-Microsoft build server, like CruiseControl.NET. NUnit has more versions coming out than visual studio. You don't have to wait years for a new version. And you don't have to install a new version of the IDE to get new features. There are extensions being developed for NUnit, like row-tests, etc. Visual Studio tests take a long time to start up for some reason. This is better in Visual Studio 2008, but it is still too slow for my taste. Quickly running a test to see if you didn't break something can take too long. NUnit with something like Testdriven.Net to run tests from the IDE is actually much faster. Especially when running single tests. According to Kjetil Klaussen, this is caused by the Visual Studio testrunner. Running MSTest tests in TestDriven.Net makes MSTest performance comparable to NUnit.

随着。net 4.0中代码契约系统的发布和静态检查器的可用性,理论上你将需要编写更少的测试用例,而像Pex这样的工具将有助于识别这些用例。将这一点与前面的讨论联系起来,如果您需要更少地使用单元测试,因为您的契约会覆盖您的尾部,那么为什么不直接使用内置组件呢,因为这样可以少管理一个依赖项。这些天来,我只追求简单。: -)

参见:

微软Pex -自动化单元测试 使用Visual Studio 2010和c# 4.0与Pex生成单元测试

xUnit是新项目的另一种可能。它的语法可能更直观,但它与其他框架并不兼容。