Take the 2-minute tour ×

I need a way to fake DateTime.Parse with Typemock and have it return the same date when called with any parameters.

I have a DB field that stores an encrypted string that is parsed as date when loaded. The class that holds the data has a Load() method where it copies DB data into its properties, decrypts what's encrypted and does some basic validation, such as:

public class BusinessObject{
    public DateTime ImportantDate{get;set;}
    public void Load(DBObject dbSource){
        ImportantDate = DateTime.Parse(DecryptionService.Decrypt(dbSource.ImportantDate));

Runtime all works well.

I'm trying to write a unit test using TypeMock to load some fake data into BusinessObject using its Load method. BusinessObject has way too many properties and can not be deserialized from XML, but DBObject can, so I've stored some XMLs that represent valid data.

It all works well until DecryptionService is called to decrypt the data - it doesn't work because my dev machine doesn't have the DB certificates used in the encryption process. I can't get those on my machine just for testing, that would be a security breach.

I added this to my unit test:

Isolate.WhenCalled(() => DecryptionService .Decrypt(null)).WillReturn("***");

Isolate.WhenCalled(() => DateTime.Parse("***"  /*DateStr*/)).WillReturn(DateTime.Now.AddYears(2));

The first part where DecryptionService is faked works, social security and other sensitive strings are "decrypting", but no matter what parameters I give to DateTime I still get one exception or another (ArgumentNullException: String reference not set to an instance of an object if DateStr is null, FormatException when it's "*")

How (if) can I override DateTime.Parse with typemock so that it returns valid DateTime with any invalid paramters passed?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

My name is Nofar and i'm from Typemock's support team.

DateTime.Parse is not supported in the WhenCalled API, so in order to fake it's returned value you need to wrap it with a method from your class, for example:

public class BusinessObject
    public DateTime Load (string s)
    return DateTime.Parse(s);  

And you test will look like this:

    public void TestMethodDateTime()
        BusinessObject b = new BusinessObject();
        DateTime now= DateTime.Now.AddYears(2);


        Assert.AreEqual(now, b.Load(null));

Supporting DateTime.Parse in the WhenCalled API is in our backlog.

Please feel free to contact us via mail at support@typemock.com

Nofar Typemock Support

share|improve this answer
add comment

Your Answer


