B
Berryl Hesh
Is there a way to pass a property around as a parameter without reflection?
My current motivation for this is the code below is testing multiple
properties to see that an exception is thrown if a user tries to set the
string value to an empty value. Ideally I'd like to have one method that
would take a Property as a parameter and test it:
[Test]
public void CompanyName_Error_CannotSetToEmpty() {
var customer = new Customer { ID = "TEST" };
try {
customer.CompanyName = string.Empty;
Assert.Fail("EmptyValueException for CompanyName property should
have been thrown.");
}
catch (EmptyValueException ex) {
_assertPropertyNameIsSetProperly(ex, "CompanyName");
}
}
[Test]
public void PhoneNumber_Error_CannotSetToEmpty() {
var customer = new Customer { ID = "TEST" };
try {
customer.Phone = string.Empty;
Assert.Fail("EmptyValueException for Phone property should have
been thrown.");
}
catch (EmptyValueException ex) {
_assertPropertyNameIsSetProperly(ex, "Phone");
}
}
private static void _assertPropertyNameIsSetProperly(EmptyValueException
ex, string expectedName) {
Assert.That(ex.PropertyName, Is.EqualTo(expectedName));
}
My current motivation for this is the code below is testing multiple
properties to see that an exception is thrown if a user tries to set the
string value to an empty value. Ideally I'd like to have one method that
would take a Property as a parameter and test it:
[Test]
public void CompanyName_Error_CannotSetToEmpty() {
var customer = new Customer { ID = "TEST" };
try {
customer.CompanyName = string.Empty;
Assert.Fail("EmptyValueException for CompanyName property should
have been thrown.");
}
catch (EmptyValueException ex) {
_assertPropertyNameIsSetProperly(ex, "CompanyName");
}
}
[Test]
public void PhoneNumber_Error_CannotSetToEmpty() {
var customer = new Customer { ID = "TEST" };
try {
customer.Phone = string.Empty;
Assert.Fail("EmptyValueException for Phone property should have
been thrown.");
}
catch (EmptyValueException ex) {
_assertPropertyNameIsSetProperly(ex, "Phone");
}
}
private static void _assertPropertyNameIsSetProperly(EmptyValueException
ex, string expectedName) {
Assert.That(ex.PropertyName, Is.EqualTo(expectedName));
}