Skip to content

Commit 70c9307

Browse files
committed
Added check and argument exception for get to property with no value
1 parent c9c9663 commit 70c9307

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

NTestDataBuilder.Tests/GetSetTests.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using NTestDataBuilder.Tests.Builders;
1+
using System;
2+
using NTestDataBuilder.Tests.Builders;
23
using NUnit.Framework;
34

45
namespace NTestDataBuilder.Tests
@@ -56,5 +57,14 @@ public void GivenAValueHasBeenSetAgainstTwoProperties_WhenRetrievingTheValueForT
5657

5758
Assert.That(retrieved, Is.EqualTo(SetValue));
5859
}
60+
61+
[Test]
62+
public void GivenNoValueHasBeenSetForAProperty_WhenRetrievingTheValueForThatProperty_ThenThrowAnException()
63+
{
64+
var ex = Assert.Throws<ArgumentException>(() => _b.Get(x => x.FirstName));
65+
66+
Assert.That(ex.Message, Is.StringStarting("No value has been recorded yet for FirstName; consider using Has(x => x.FirstName) to check for a value first."));
67+
Assert.That(ex.ParamName, Is.EqualTo("property"));
68+
}
5969
}
6070
}

NTestDataBuilder/DataBuilder.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,29 @@ public void Set<TValue>(Expression<Func<TEntity, TValue>> property, TValue value
5353
/// <returns>The recorded value of the property</returns>
5454
public TValue Get<TValue>(Expression<Func<TEntity, TValue>> property)
5555
{
56+
if (!Has(property))
57+
throw new ArgumentException(
58+
string.Format(
59+
"No value has been recorded yet for {0}; consider using Has(x => x.{0}) to check for a value first.",
60+
GetPropertyName(property)
61+
),
62+
"property"
63+
);
64+
5665
return (TValue)_properties[GetPropertyName(property)];
5766
}
5867

68+
/// <summary>
69+
/// Returns whether or not there is currently a value recorded against the given property from <see cref="TEntity"/>.
70+
/// </summary>
71+
/// <typeparam name="TValue">The type of the property</typeparam>
72+
/// <param name="property">A lambda expression specifying the property to retrieve the recorded value for</param>
73+
/// <returns>Whether or not there is a recorded value for the property</returns>
74+
protected bool Has<TValue>(Expression<Func<TEntity, TValue>> property)
75+
{
76+
return _properties.ContainsKey(GetPropertyName(property));
77+
}
78+
5979
private static string GetPropertyName<TValue>(Expression<Func<TEntity, TValue>> property)
6080
{
6181
var memExp = property.Body as MemberExpression;

0 commit comments

Comments
 (0)