views:

632

answers:

5

Is there a "#if DEBUG"-like conditional statement which can be used in VS 2008 for determining if the code is being run from a unit test? (We're using MS's built-in unit testing.)

For example:

#if !UNITTEST

// Do some GUI stuff we don't want to see when unit testing

#endif

A: 

Note that any such definition is only meaningful at compilation time. Hence you'd have to compile it one way to get the code, and another way to have that code removed. So, you code would be "sensing" that it's being run by the unit test framework. You'd need two separate assemblies. If that's really what you want, it's easy enough to define a symbol. Just go to Project Properties, "Build" tab, and add "UNITTEST" under Conditional Compilation Symbols.

James Curran
A: 

I agree with the comments saying to avoid doing this in general - but I've done this in the past myself. IIRC, it was used to switch between a "unit test database" (i.e. throwaway) and a "test database with useful data in" - which had been accidentally wiped by unit tests one too many times...

Our solution was to have a UnitTestDetector class (or something like that) which had a single static property, "InUnitTest". This would be detected by whether NUnit was loaded in the current appdomain (again, IIRC). After the first probing, the result would be cached to prevent it from being a performance hit.

Jon Skeet
+1  A: 

The conditional statement you are talking about is not available because it is a compiler directive; You'd have to have a test specific build, which you could define your own TEST compiler directive. However, as the commenters noted - You shouldn't run different code for a test than you would in production, defeats the purpose.

Chris Shaffer
+1  A: 

Thank you. Avoiding the use of unit test-specific code was the approach I was planning to take, but was talked into looking down this route in case it existed. Now I won't do it! :)

A: 

+1 for Chris' answer. This sounds like a good place for a "Test Fake" or "Test Double" type class. Can you extract the GUI stuff you want to hide into virtual or abstract methods, and then create (in your test project) a class that derives from the class under test and overrides the GUI code?

Seth Petry-Johnson