Created
October 12, 2011 07:46
-
-
Save jauco/1280552 to your computer and use it in GitHub Desktop.
A object templator for your unittests, like factorygirl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Blueprint { | |
public class Blueprint<T> { | |
Func<IdGenerator, T> constructor; | |
//IdGenerator is static, so all objects of type T will have a different Id | |
private static IdGenerator idgen = new IdGenerator(); | |
public Blueprint(Func<IdGenerator, T> constructor) { | |
this.constructor = constructor; | |
} | |
public Blueprint<T> With(Action<T> modifier) { | |
return new Blueprint<T>((idGenParam) => { | |
var obj = constructor(idGenParam); | |
modifier(obj); | |
return obj; | |
}); | |
} | |
public T Create() { | |
return constructor(idgen); | |
} | |
public T Create(Action<T> modifier) { | |
var o = constructor(idgen); | |
modifier(o); | |
return o; | |
} | |
} | |
public class IdGenerator { | |
private int iter = 0; | |
public int Next() { | |
return iter++; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq.Expressions; | |
using System.Diagnostics; | |
namespace Blueprint { | |
public class Blueprintusage { | |
public Blueprintusage() { | |
//Blueprint | |
var skeet = new Blueprint<Person>((idGen) => new Person { | |
//Unique Id's | |
Id = idGen.Next(), | |
LastName = "Skeet", | |
}); | |
//Override properties | |
Blueprint<Person> writerSkeet = skeet.With(p => { | |
p.Job = "Writer"; | |
}); | |
Blueprint<Person> coderSkeet = skeet.With(p => { | |
p.Job = "Coder Extraordinaire"; | |
}); | |
//Dynamic properties | |
Blueprint<Person> oldWriterSkeet = skeet.With(p => { | |
p.Age = (DateTime.Now - new DateTime(1920, 11, 10)).Hours / 365; //Will be evaluated each time when Create is called | |
}); | |
Person someGenericWriterSkeet = writerSkeet.Create(); | |
Person JohnSkeet = skeet.Create(x => x.FirstName = "Jon"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Blueprint { | |
public class Person { | |
public int Id; | |
public string FirstName; | |
public string LastName; | |
public string Job; | |
public int Age; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment