In a recent stubbing question, many answers suggested C # interfaces or delegates to implement stubs, but one answer suggested using conditional compilation while maintaining static binding in production code.This answer was changed to -2 while reading, so at least 2 people actually considered That is the wrong answer. Perhaps the misuse of DEBUG was the cause, or perhaps the use of a fixed cost instead of a broader review. But I cannot help but wonder:
Is using conditional compilation an unacceptable method for implementing unit test stubs? Sometimes? Always?
Thanks.
Edit-add: I would like to add an example as an experimental experiment:
class Foo { public Foo() { .. } private DateTime Now { get { #if UNITTEST_Foo return Stub_DateTime.Now; #else return DateTime.Now; #endif } }
compared with
interface IDateTimeStrategy { DateTime Now { get; } } class ProductionDateTimeStrategy : IDateTimeStrategy { public DateTime Now { get { return DateTime.Now; } } } class Foo { public Foo() : Foo(new ProductionDateTimeStrategy()) {} public Foo(IDateTimeStrategy s) { datetimeStrategy = s; .. } private IDateTime_Strategy datetimeStrategy; private DateTime Now { get { return datetimeStrategy.Now; } } }
This allows you to disable the outbound dependency on "DateTime.Now" through the C # interface. However, we added a dynamic dispatch call, where static would be sufficient, the object is larger even in the production version, and we added a new failure path for the Foo constructor (selection may fail).
Am I not worried about anything here? Thanks for the feedback!
Aaron source share