Why mock a regex?
While regex is an internal dependency of your Luhn implementation, it's not a dependency that should be injected, and therefore should not be mocked.
If doing a Luhn check is a dependency on your validation code, and what to validate that it does do a Luhn check, you could have an interface / abstract class, where an implementation could do regex internally.
A possibility could be
interface ICardValidator
{
bool IsCardValid(string cardNumber);
}
class LuhnCardValidator : ICardValidator
{
private static readonly Regex _cardRegex = new Regex(...);
bool IsCardValid(string cardNumber)
{
return Regex.IsMatch(cardNumber);
}
}
You can write unit tests against LuhnCardValidator
to verify that your Luhn check works.
[Test]
[TestCase("4242424242424242")
public void ShouldBeValid(string cardNumber)
{
Assert.IsTrue(new LuhnCardValidator().IsCardValid(cardNumber));
}
You can also write tests against your code that depends on ICardValidator
to say for example when validation fails it presents the user the appropriate error message.
[Test]
public void ShouldPresentCardFailedMessage()
{
var mockCardValidator = new Mock<ICardValidator>();
mockCardValidator.Setup(x => x.IsCardValid(It.IsAny<string>()).Returns(false);
var validationSummary = new ValidationSummary(mockCardValidator.Object);
validationSummary.ValidateThePage(...);
var errors = validationSummary.GetErrors();
Assert.IsTrue(errors.Any(x => x.Message == "Credit card number is not valid"));
}