Reputation: 5824
In our application we enforce that all dates stored as strings should be in ISO 8601 format. So, for example if we are storing a date in a Lucene index I want to ensure that it is always stored in the format:
2014-03-12T23:03:13Z
We have an extension method DateTime.ToISO8601DateTimeString()
to make this easy along with unit testing around existing code ensuring this is always the case.
I wonder however whether it is possible to ensure DateTime.ToString()
is never called in code (With the exception of it's overloads)?
Possible routes:
DateTime.ToString()
with an exceptionHas anyone successfully achieved this in the past with a similar method?
To clarify, I want this to be application wide and automatically fail if new code is added anywhere in a project calling DateTime.ToString()
Upvotes: 2
Views: 279
Reputation: 52133
Using Moq (most mocking frameworks have this feature).
// Method should never be called
mock.Verify(foo => foo.Execute("ping"), Times.Never());
If you can't mock your method (because is not an interface) you can try using microsoft fakes (moles) to do the work.
Simply put an assert.Fail inside the Mole so that it will fail the test if called.
Edit: As @Euphoric said you should have a good reason to do that. However with that said you can use moles to produce the expected result. Using MS Test Fakes:
using (ShimsContext.Create())
{
System.Fakes.ShimDateTime.NowGet = () => Assert.Fail("DateTime.Now called");
}
Upvotes: 4
Reputation: 12849
This might be OT, but I really think you should not do this.
The correct way to do this is to create CustomDate
class, that is used in your application instead of DateTime
. If you ensure the application can't accept DateTime
and that CustomDate
uses the conversion you want then there is no need to do any kind of testing.
And note, that this code will not trigger your test, yet will bring problem:
DateTime now = DateTime.Now;
String str = "now is :"+now;
Upvotes: 5