开发者

Detect if Visual Studio Test is running

开发者 https://www.devze.com 2022-12-25 15:48 出处:网络
Is there an easy way to detect if you\'re running in the context of a Visual Studio Test as opposed to debug or release?

Is there an easy way to detect if you're running in the context of a Visual Studio Test as opposed to debug or release?

Here's the scenario - we have a factory class that we use heavily through开发者_如何转开发out our existing codebase, and I figured instead of refactoring it out in each class so we can substitute the default factory with one that would return mock/fake objects, I could add something in the factory class itself to return those mock objects if it detects it's running in "test" mode.


I don't think it's a good idea to mix test case code with domain code.

I suggest you provide an Interface for your factory, and implement mocks for that interface for testing purposes.

Even better, you may use a mocking framework such as RhinoMocks.


I agree with mcabral's assessment with reference to the reasons (I think the refactoring is worth it), but as far as the mechanics go...

In Visual Studio you can define any number of configurations other than "Debug" and "Release," at both the solution and project level. So, you could create a "Testing" configuration, most likely based on the Debug configuration. Next create a "Testing" configuration in the project that contains the factory class.

In the project properties window, select the "Build" tab. Select the "Testing" configuration and define a conditional compilation symbol: "TESTING".

Now in your code you can use

#if TESTING
     // build stubs
#else
     // build real implementations
#endif


You can test the current process executable. Its not very elegant, but it works.

if (Process.GetCurrentProcess().ProcessName.ToLower().Contains("vstest.executionengine"))
{
  // we are in a ms unit test
}
else
{
  // normal programm execution
}


Have you heard of Dependency Injection or IOC? This situation is what they are for.

As such, I'd suggest using an IOC container to provide your objects rather than a custom factory. If you have special requirements for some of them, you can put the factory in the IOC container.

You can then configure the container differently in your tests (or not use it at all) and that code will stay out of your main code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号