views:

49

answers:

3

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 throughout 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.

+3  A: 

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.

mcabral
Yeah, that's our alternative. We're just getting our main codebase into TDD and trying to avoid the larger headaches like modifying every model class, so I figured I would ask. We are planning on using a mocking framework, have been playing with NMock.
RTigger
A: 

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
Jay
Yeah, that would work. I was thinking something closer to how you can call HttpContext.Current.IsDebuggingEnabled, but for testing. I will probably go the refactor route since we'll have to do it eventually anyways. Thanks for the suggestion.
RTigger
A: 

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.

Orion Edwards