C
C#10mo ago
mejobloggs

✅ Easier way to "mark" a class as a different "type" without having to create a new class?

Sorry about the title, I'm not sure of the correct terminology Here's my scenario I have a basic class
public class ValidationResult
{
public ValidationResult(bool isValid, string? errorMessage = null)
{
IsValid = isValid;
ErrorMessage = errorMessage;
}

public bool IsValid { get; set; }
public string? ErrorMessage { get; set; }
}
public class ValidationResult
{
public ValidationResult(bool isValid, string? errorMessage = null)
{
IsValid = isValid;
ErrorMessage = errorMessage;
}

public bool IsValid { get; set; }
public string? ErrorMessage { get; set; }
}
Which is fine, I can display the reason for failure to the user. But I notice when trying to create some unit tests, I'm trying to test for specific failures, and the test might pass because of a different failure... which isn't a proper test then. The test could say Assert.IsTrue(validation.ErrorMessage == "Failure because Reason 1") But then the test would break if I updated the error message. I could have an IValidationResult, then have e.g 10 different classes all exactly the same, inheriting from IValidationResult Then my test could say (pseudocode) Assert.IsTrue(validation is Reason1ValidationResult) That would be less fragile which is good, but then I have to create a bunch of identical classes (except for the name) Is there a better/simpler way to do this?
5 Replies
Pobiega
Pobiega10mo ago
Use an enum for why it failed?
Tvde1
Tvde110mo ago
either an enum or a const string that you reference seems smart in a shared project
Azrael
Azrael10mo ago
Enum or constants.
mejobloggs
mejobloggs10mo ago
Enums it is then, thanks guys
Accord
Accord10mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.