-
Notifications
You must be signed in to change notification settings - Fork 0
Validation Class for unit tests
Lisa Malenfant edited this page Dec 18, 2023
·
4 revisions
This validation class will iterate through an object so it can compare value types to make sure they match. This is useful when mocking methods that do not return a value so you can validate that an object contained the correct values. The Assert may need adjusting, depending on the test framework you are using.
namespace MoqToNSubstitute.Tests.Helpers
{
/// <summary>
/// Unit test validation methods
/// </summary>
public static class Validation
{
/// <summary>
/// Takes 2 objects of type T and makes sure the ValueTypes are equal
/// </summary>
/// <typeparam name="T">The type of object to compare</typeparam>
/// <param name="expected">The object with the expected values</param>
/// <param name="actual">The object with the actual values</param>
/// <returns>True if the objects are the same, false otherwise</returns>
public static bool Validate<T>(T expected, T actual) where T : class?
{
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
var expectedValue = property.GetValue(expected);
var actualValue = property.GetValue(actual);
// We need to check the type against value type and string because string is reference type
if (expectedValue == null || expectedValue.GetType().IsValueType || expectedValue is string)
{
Assert.AreEqual(expectedValue, actualValue);
}
else
{
Validate(expectedValue, actualValue);
}
}
return true;
}
}
}_codeTransformation.Received(1).Modify(Arg.Is<CodeSyntax>(p => Validation.Validate(_substitutions, p)));