且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有用于以编程方式运行Visual Studio单元测试的API?

更新时间:2023-02-20 20:30:28

您是正确的,因为没有用于mstest框架的公共API.我有一天为mstest编写了一份手动替代品,以查看它的难易程度,而且它并不像看起来那样简单(特别是如果您想利用多个CPU内核),因此请当心这条路.>

我个人始终总是以编程方式运行mstest.exe,然后解析生成的.trx XML文件.有什么特殊原因导致您无法使用Process.Start来运行它?

P.S.如果您通过/noisolation命令行参数,则可以解决mstest.exe的某些奇怪行为-如果您感觉很倾斜,请尝试一下:-)


更新:Erik提到他想在当前线程中运行测试API,以便为全球化问题设置线程区域性.

如果在调试器下运行单元测试,您会注意到mstest创建了一堆线程,并在不同的线程中运行所有测试,因此即使您可以访问API,也不太可能.

我建议这样做:

  1. 在测试的运行程序"应用程序中,设置环境变量
  2. 运行mstest将其指向特定的测试
  3. 添加[ClassInitialize](或[TestInitialize])方法,该方法读取此环境变量并设置区域性
  4. 利润!

Is there an API for running Visual Studio Unit Tests programmatically?

Running MSTests.exe with Process.Start() does not work in the current scenario. What I'm looking for is something like the NUnit SimpleTestRunner.

Any ideas?

/Erik

You're correct in that there's no public API for the mstest framework. I wrote a manual replacement for mstest one day to see how hard it was, and it's not as simple as it looks (particularly if you want to take advantage of more than one CPU core), so beware of going down this path.

Personally I've always just run mstest.exe programatically and then parsed the resulting .trx XML file. Are there any particular reasons why you can't use Process.Start to run it?

P.S. Some of the strange behaviour of mstest.exe are solved if you pass the /noisolation command line parameter - give that a go if you feel so inclined :-)


Update: Erik mentions he wants to run the test API in the current thread so he can set the thread culture for globalization issues.

If you run a unit test under the debugger, you'll notice that mstest creates a bunch of threads, and runs all your tests in different threads, so this isn't likely to work even if you could access the API.

What I'd suggest doing is this:

  1. From your test "runner" application, set an environment variable
  2. Run mstest pointing it at the specific tests
  3. Add a [ClassInitialize] (or [TestInitialize]) method which reads this environment variable and sets the culture
  4. Profit!