So, I have my own implementation of Luhn's algorithm and I'm using a Regular Expression to validate the User's input.
I proceed to do the unit testing, and I'm finding myself in this problem:
Mock<Regex> regexMock = new Mock<Regex>();
regexMock.Setup(r => r.IsMatch(It.IsAny<string>())).Returns(true);
Note: I'm using Moq framework to do the mocking
But somehow, the last line of code is throwing an Exception
Invalid setup on a non-virtual (overridable in VB) member: r => r.IsMatch(It.IsAny<string>())
I would like to know what alternatives do I have to solve my problem of mocking, or maybe some workaround that can be made.
Thanks in advance!
Edit:
Ok, so my Test looks like this:
Mock<Regex> regexMock = new Mock<Regex>();
regexMock.Setup(r => r.IsMatch(It.IsAny<string>())).Returns(true);
Mock<IRegexBuilder> builderMock = new Mock<IRegexBuilder>();
builderMock.Setup(m => m.Build()).Returns(regexMock.Object);
LuhnAlgorithm luhn = new LuhnAlgorithm(builderMock.Object);
string input = "7992739871";
ushort expected = 3;
object output = luhn.GenerateChecksum(input);
Assert.IsInstanceOfType(output, typeof(ushort));
Assert.AreEqual(expected, (ushort)output);
I have this IRegexBuilder which is another class I made to help the creation of Regex. What it is important is that the final Regex object is made with a call to the IRegexBuilder.Build() method.
Now, I can mock that method and return a fixed Regex, like:
builderMock.Setup(m => m.Build()).Returns(new Regex("\d+"));
but I don't want to define my validation on the Test.
Guys, I want my validation (however it is made) to not influence my testing, I would like to mock the input matching to return true or false, independently of how the validation is made. If I create my own Regex in the Test Method, then whenever I change my validation logic in the future, I would have to change the Test.