Note that there are some explanatory texts on larger screens.

plurals
  1. POIs conditional compilation a valid mock/stub strategy for unit testing?
    primarykey
    data
    text
    <p>In a recent question on stubbing, many answers suggested C# interfaces or delegates for implementing stubs, but <a href="https://stackoverflow.com/questions/43711/whats-a-good-way-to-overwrite-datetimenow-during-testing#43718">one answer</a> suggested using conditional compilation, retaining static binding in the production code. This answer was modded -2 at the time of reading, so at least 2 people really thought this was a <em>wrong</em> answer. Perhaps misuse of DEBUG was the reason, or perhaps use of fixed value instead of more extensive validation. But I can't help wondering:</p> <p>Is the use of conditional compilation an inappropriate technique for implementing unit test stubs? Sometimes? Always?</p> <p>Thanks.</p> <p><strong>Edit-add:</strong> I'd like to add an example as a though experiment:</p> <pre><code>class Foo { public Foo() { .. } private DateTime Now { get { #if UNITTEST_Foo return Stub_DateTime.Now; #else return DateTime.Now; #endif } } // .. rest of Foo members } </code></pre> <p>comparing to</p> <pre><code>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; } } } </code></pre> <p>Which allows the outgoing dependency on "DateTime.Now" to be stubbed through a C# interface. However, we've now added a dynamic dispatch call where static would suffice, the object is larger even in the production version, and we've added a new failure path for Foo's constructor (allocation can fail). </p> <p>Am I worrying about nothing here? Thanks for the feedback so far!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload