Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Support strongly typed Define and Create methods

You can now define blueprints (and create objects too) using the following
syntax:

    p.DefinePropertiesOf(new Person {
      FirstName = "James"
    });
    p.Create(new Person { FirstName = "James" });

This approach is strongly typed, and prevents some of the typo and
refactoring induced errors that can occur from using anonymous objects.
Obviously, this approach is only applicable if your object has a default
constructor (and doesn't do anything nasty in there).
  • Loading branch information...
commit 14031bf92129c82b2c7b4406f052291ab835b98c 1 parent ab689e9
@jagregory authored James Gregory committed
Showing with 26 additions and 0 deletions.
  1. +10 −0 Plant.Core/BasePlant.cs
  2. +16 −0 Plant.Tests/BasePlantTest.cs
View
10 Plant.Core/BasePlant.cs
@@ -57,6 +57,11 @@ private static T CreateInstanceWithEmptyConstructor<T>()
return Activator.CreateInstance<T>();
}
+ public virtual T Create<T>(T userSpecifiedProperties)
+ {
+ return Create<T>((object)userSpecifiedProperties);
+ }
+
public virtual T Create<T>(object userSpecifiedProperties = null)
{
var userSpecifiedPropertyList = ToPropertyList(userSpecifiedProperties);
@@ -138,6 +143,11 @@ public virtual void DefinePropertiesOf<T>(object defaults, Action<T> afterProper
DefinePropertiesOf<T>(defaults);
postBuildActions[typeof (T)] = afterPropertyPopulation;
}
+
+ public virtual void DefinePropertiesOf<T>(T defaults)
+ {
+ DefinePropertiesOf<T>((object)defaults);
+ }
public virtual void DefinePropertiesOf<T>(object defaults)
{
View
16 Plant.Tests/BasePlantTest.cs
@@ -44,6 +44,22 @@ public void Should_Create_Instance_With_Null_Value()
}
[Test]
+ public void Should_Create_Instance_With_Default_Properties_Specified_By_Instance()
+ {
+ var testPlant = new BasePlant();
+ testPlant.DefinePropertiesOf(new Person { FirstName = "James" });
+ Assert.AreEqual("James", testPlant.Create<Person>().FirstName);
+ }
+
+ [Test]
+ public void Should_Create_Instance_With_Requested_Properties_Specified_By_Instance()
+ {
+ var testPlant = new BasePlant();
+ testPlant.DefinePropertiesOf(new Person { FirstName = "David" });
+ Assert.AreEqual("James", testPlant.Create(new Person { FirstName = "James" }).FirstName);
+ }
+
+ [Test]
[ExpectedException(typeof(PropertyNotFoundException))]
public void Should_Throw_PropertyNotFound_Exception_When_Given_Invalid_Property()
{
Please sign in to comment.
Something went wrong with that request. Please try again.