Skip to content

Instantly share code, notes, and snippets.

@mattfrear
Last active November 7, 2018 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattfrear/b555286dd5767cea632c003111ec0334 to your computer and use it in GitHub Desktop.
Save mattfrear/b555286dd5767cea632c003111ec0334 to your computer and use it in GitHub Desktop.
With method for setting any property on any object including read only properties (for tests)
public static class ObjectExtensions
{
public static T With<T, TProp>(this T o, Expression<Func<T, TProp>> prop, TProp value)
{
if (!(prop.Body is MemberExpression memberExpression))
{
throw new ArgumentException($"A property must be provided. ({prop})");
}
var propertyInfo = (PropertyInfo) memberExpression.Member;
if (propertyInfo.CanWrite)
{
propertyInfo.SetValue(o, value);
}
else
{
typeof(T).GetField($"<{propertyInfo.Name}>k__BackingField",
BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(o, value);
}
return o;
}
}
@mattfrear
Copy link
Author

Example usage:

    public class Advisor
    {
        public Advisor(
            string advisorEmailAddress,
            string administratorEmailAddress,
            AuthorizationType authorizationType, 
            IntroducerType introducerType, 
            IEnumerable<LenderBrokerCode> lenderBrokerCodes, 
            IEnumerable<LenderBrokerCode> administratorLenderBrokerCodes)
        {
            LenderBrokerCodes = lenderBrokerCodes;
            AdvisorEmailAddress = advisorEmailAddress;
            AuthorizationType = authorizationType;
            IntroducerType = introducerType;
            AdministratorLenderBrokerCodes = administratorLenderBrokerCodes;
            AdministratorEmailAddress = administratorEmailAddress;
        }

        public string AdvisorEmailAddress { get; }
        public string AdministratorEmailAddress { get; }
        public AuthorizationType AuthorizationType { get; }
        public IntroducerType IntroducerType { get; }
        public IEnumerable<LenderBrokerCode> LenderBrokerCodes { get; }
        public IEnumerable<LenderBrokerCode> AdministratorLenderBrokerCodes { get; set; }
    }

then in your test:

var aggregator = fixture.Create<Aggregator>();
aggregator.With(a => a.AdvisorEmailAddress, "test@test.com");

This saves you from inventing dummy data for all the constructor parameters which you don't care about.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment