Skip to content

Commit

Permalink
Add read only property support
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthewMooreZA committed Jan 20, 2019
1 parent a91b17e commit bc314ae
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
8 changes: 8 additions & 0 deletions Giver.Tests/ComplexTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ public void With_Many() {

Assert.Equal(testModels.Count, 5);
}

[Fact]
public void ReadOnly_Property()
{
OrderLine orderLine = _give.Me<OrderLine>();

Assert.Equal(orderLine.Price * orderLine.Quantity, orderLine.TotalPrice);
}
}

public class CustomStringGenerator: StringGenerator {
Expand Down
14 changes: 14 additions & 0 deletions Giver.Tests/Model/OrderLine.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Giver.Tests.Model
{
public class OrderLine
{
public int Id { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public decimal TotalPrice => Price * Quantity;
}
}
11 changes: 10 additions & 1 deletion Giver/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public static List<Member> GetPrimitiveMembers<T>() {
#else
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
#endif
.Where(p => IsPrimitive(p.PropertyType))
.Where(p => IsPrimitive(p.PropertyType) && p.HasSetter())
.Select(p => new Member(p, p.PropertyType))
#if NET_40
.Union(type.GetFields()
Expand All @@ -34,6 +34,15 @@ public static bool IsPrimitive(Type type) {
#endif
}

public static bool HasSetter(this PropertyInfo propertyInfo)
{
#if NET_40
return propertyInfo.GetSetMethod() != null;
#else
return propertyInfo.SetMethod != null;
#endif
}

public static void SetValue(object instance, MemberInfo memberInfo, object value) {
var propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null) {
Expand Down

0 comments on commit bc314ae

Please sign in to comment.