From 1b863d090db2768762b6315b28fe6c08d89ed08b Mon Sep 17 00:00:00 2001 From: Jake Soenneker Date: Fri, 9 Feb 2024 15:01:13 -0600 Subject: [PATCH] Excludes constants in automembers --- src/AutoFakerBinder.cs | 22 +++++++++++++------ src/Soenneker.Utils.AutoBogus.csproj | 2 +- .../Dtos/Complex/Order.cs | 6 ++++- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/AutoFakerBinder.cs b/src/AutoFakerBinder.cs index e26bf79..2499a2b 100644 --- a/src/AutoFakerBinder.cs +++ b/src/AutoFakerBinder.cs @@ -50,7 +50,7 @@ public AutoFakerBinder(AutoFakerConfig autoFakerConfig) if (cachedParameters.Length == 0) { - return (TType?)constructor.Invoke(); + return (TType?) constructor.Invoke(); } var parameters = new object[cachedParameters.Length]; @@ -231,16 +231,24 @@ private List GetMembersToPopulate(CachedType cachedType) for (var i = 0; i < properties.Length; i++) { + if (properties[i].IsConstant()) + continue; + PropertyInfo property = properties[i]; autoMembers.Add(new AutoMember(property, _autoFakerConfig)); } - for (var i = 0; i < fields.Length; i++) + if (fields != null) { - FieldInfo field = fields[i]; - autoMembers.Add(new AutoMember(field, _autoFakerConfig)); - } + for (var i = 0; i < fields.Length; i++) + { + if (fields[i].IsConstant()) + continue; + FieldInfo field = fields[i]; + autoMembers.Add(new AutoMember(field, _autoFakerConfig)); + } + } _autoMembersCache.TryAdd(cachedType, autoMembers); return autoMembers; @@ -255,7 +263,7 @@ private static void PopulateDictionary(object value, object parent, AutoMember m CachedType[] argTypes = member.CachedType.GetAddMethodArgumentTypes(); CachedMethod? addMethod = GetAddMethod(member.CachedType, argTypes); - if (instance == null || addMethod == null) + if (instance == null || addMethod == null) return; foreach (object? key in dictionary.Keys) @@ -273,7 +281,7 @@ private static void PopulateCollection(object value, object parent, AutoMember m CachedType[] argTypes = member.CachedType.GetAddMethodArgumentTypes(); CachedMethod? addMethod = GetAddMethod(member.CachedType, argTypes); - if (instance == null || addMethod == null) + if (instance == null || addMethod == null) return; foreach (object? item in collection) diff --git a/src/Soenneker.Utils.AutoBogus.csproj b/src/Soenneker.Utils.AutoBogus.csproj index 4f4515f..6150f30 100644 --- a/src/Soenneker.Utils.AutoBogus.csproj +++ b/src/Soenneker.Utils.AutoBogus.csproj @@ -42,7 +42,7 @@ - + diff --git a/test/Soenneker.Utils.AutoBogus.Tests/Dtos/Complex/Order.cs b/test/Soenneker.Utils.AutoBogus.Tests/Dtos/Complex/Order.cs index 3efb001..fdaf64a 100644 --- a/test/Soenneker.Utils.AutoBogus.Tests/Dtos/Complex/Order.cs +++ b/test/Soenneker.Utils.AutoBogus.Tests/Dtos/Complex/Order.cs @@ -6,7 +6,11 @@ namespace Soenneker.Utils.AutoBogus.Tests.Dtos.Complex; public sealed class Order { public DateTime Timestamp; - + + private int _privateFieldId; + + public const string Constant = "Order2x89ei"; + public Order(int id, ICalculator calculator) { Id = id;