Mocking Regex.IsMatch() - c#

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.

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"));
}

If the regular expression represents a complex algorithm, you could encapsulate the matching in a custom class with an interface and dependency-inject that (or a mock of that).
If it's basic validation, I wouldn't mock it at all. Would you mock String.Contains()?

When you are creating mock with Moq, it creates class which implements interface you are mocking, or class inherited from class which you are mocking. This generated class should provide its own implementation of member you are mocking. With interface its simple, because there is no implementation. With class member should be abstract or virtual. Regex.IsMatch is not abstract, nor virtual. So Moq just can't create its own implementation of this member in order to make setup.
You should use something which Moq can handle. Usually some wrapper class which has virtual methods or implements some interface. This class should delegate work to Regex class:
public interface IWrapper // use appropriate name of interface
{
bool IsValid(string value)
}
This interface can be easily mocked. You can now write tests for clients which use this interface. For real life you will need implementation which delegates work to Regex:
public class Wrapper : IWrapper
{
public bool IsValid(string value)
{
// use Regex here
}
}

Related

NSubstitute ForPartsOf calling concrete implementation event when substituted

I have the following class:
public class MyClass : IMyClass
{
public string MyFunc(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new Exception("Blank Name");
}
return name;
}
public double MyFuncWrapper(string name)
{
var value = MyFunc(name);
return value;
}
In trying to test it, I was under the impression that NSubstitute's ForPartsOf effectively subclassed my class and replaced the flagged methods; so I did this:
[Fact]
public void TestMyFuncWrapper()
{
// Arrange
var myClass = Substitute.ForPartsOf<MyClass>();
myClass.MyFunc(Arg.Any<string>()).Returns("Test");
// Act
var result = myClass.MyFuncWrapper("");
// Assert
Assert.Equal("Test", result);
}
However, I get the exception raised from, what I understood to be, my substituted method. Oddly, it appears that the following line:
myClass.MyFunc(Arg.Any<string>()).Returns("Test");
Is actually calling the concrete function immediately. Looking here, it appeared that a construct like this may solve the problem (although it does use the phrase "playing it safe" which sounds quite vague):
myClass.When(a => a.MyFunc(Arg.Any<string>())).DoNotCallBase();
However, calling this actually invokes MyFunc immediately in the same way. Clearly I'd misunderstood the ForPartsOf method; my question is: can I do what I'm attempting using NSubstitute, or do I need to resort to manually subclassing MyClass?
This is by design for NSubstitute (and for most mocking frameworks).
The docs state:
For starters, NSubstitute can only work with virtual members of the
class, so any non-virtual code in the class will actually execute!
Thus, you need to add virtual to the function declarations you plan to mock.
Or (as per the docs):
If possible, stick to substituting interfaces.

Polymorphism and explicit Casting

I have the following architecture(the analogy sucks but W/E).
In program and other logic classes I have lots of methods that uses the specific type of the finger (MonkeyFinger). This mean that i have to explicitly cast in all those testMethods.
Is there any design pattern/solution to avoid explicit casts?
EDIT Code:
Monkey govi = new Monkey(...)
Program test = new Program()
test.testFinger1((MonkeyFinger) govi.GetHand.getFinger)
...
You can try something like this:
public class Animal<TFingerType> where TFingerType : IFinger
{
Hand<TFingerType> GetHand()
{
//... Do something
}
}
public class Monkey : Animal<MonkeyFinger> { }
public class Hand<TFingerType> where TFingerType : IFinger
{
}
public interface IFinger
{
}
public class MonkeyFinger : IFinger {
}
At least in your given example, it doesn't make sense for a Monkey to return a hand which contains HumanFingers. The hand itself is really defined by what type of fingers it has.
Then your code becomes:
Monkey govi = new Monkey(...)
Program test = new Program()
test.testFinger1(govi.GetHand.getFinger() /* getFinger here returns a MonkeyFinger */)
Note that the fingers are still IFingers, and can be used in that context, but this approach also provides concretely typed fingers.
I think it is best to create a method to do the checking for you. And yes, the casting is necessary if you want to test on some assumptions (like a monkey having only monkey fingers).
Something like:
public static T TestAndConvert<T>(object o)
{
Assert.IsInstanceOfType(o, typeof(T));
return (T)o;
}
Here you first check if the type is correct and then you return a typed instance. This way you are sure the type is correct and you have proper testing.
Use it in your test calls:
testFinger1(TestAndConvert<MonkeyFinger>(finger));
(From your diagram I am not sure if you use an automated test framework, like Unit Tests in Visual Studio, I recommend to do so)
Is there a real need to pass concrete finger to test method? When you are using interface you are define a contract which each implementation should follow. You can extend parent behavior in child class (or replace it but it's not correspondent with Liskov substitution principle) with method overriding but you test only contract then why do you need to pass MonkeyFinger insted of IFinger in test method?

What does it mean to "Test to the Interface"?

I know this is kindof a generic programming question, but I have Googled it on several occasions in the past and I have never found a firm answer.
Several months back I had a conversation about Interfaces with a senior engineer at another company. He said he prefers to write Interfaces for everything because (among other things) it allows him to "test to the interface". I didn't think about the phrase too much at the time, (if I had I would have just asked him to explain!) but it confused me a bit.
I think this means he would write a unit test based on the interface, and that test would then be used to analyze every implementation of the interface. If thats what he meant, it makes sense to me. However, that explanation still left me wondering what the best practice would be when, for example, one of your implementations exposes additional public methods that are not defined in the interface? Would you just write an additional test for that class?
Thanks in advance for any thoughts on the subject.
Are you sure he said test to the interface and not program to the interface?
In very simple terms what program to an interface means is that your classes should not depend on a concrete implementation. They should instead depend on an interface.
The advantage of this is that you can provide different implementations to an interface, and that enables you to unit test your class because you can provide a mock/stub to that interface.
Imagine this example:
public class SomeClass{
StringAnalyzer stringAnalizer = new StringAnalizer();
Logger logger = new Logger();
public void SomeMethod(){
if (stringAnalyzer.IsValid(someParameter))
{
//do something with someParameter
}else
{
logger.Log("Invalid string");
}
}
}
Contrast that with this one:
class SomeClass
{
IStringAnalyzer stringAnalizer;
ILogger logger;
public SomeClass(IStringAnalyzer stringAnalyzer, ILogger logger)
{
this.logger = logger;
this.stringAnalyzer = stringAnalyzer;
}
public void SomeMethod(string someParameter)
{
if (stringAnalyzer.IsValid(someParameter))
{
//do something with someParameter
}else
{
logger.Log("Invalid string");
}
}
}
This enables you to write tests like this:
[Test]
public void SomeMethod_InvalidParameter_CallsLogger
{
Rhino.Mocks.MockRepository mockRepository = new Rhino.Mocks.MockRepository();
IStringAnalyzer s = mockRepository.Stub<IStringRepository>();
s.Stub(s => s.IsValid("something, doesnt matter").IgnoreParameters().Return(false);
ILogger l = mockRepository.DynamicMock<ILogger>();
SomeClass someClass = new SomeClass(s, l);
mockRepository.ReplayAll();
someClass.SomeMethod("What you put here doesnt really matter because the stub will always return false");
l.AssertWasCalled(l => l.Log("Invalid string"));
}
Because in the second example you depend on interfaces and not concrete classes, you can easily swap them by fakes in your tests. And that is only one of the advantages, in the end it boils down to that this approach enables you to take advantage of polymorphism and that is useful not only for tests, but for any situation where you may want to provide alternative implementations for the dependencies of your class.
Full explanation of the example above can be found here.
Testing to an interface - while I've never heard that terminology before - would basically mean that while you test a concrete implementation of your interface, you only test the methods provided BY that interface. For example, consider the following classes:
interface A
{
int MustReturn3();
}
class B : A
{
public int MustReturn3()
{
return Get3();
}
public int Get3()
{
return 2 + 1;
}
}
When you want to test an implementation of A, what do you test?
Well, my implementation is B. I want to make sure that B accomplishes the tasks of A as it is supposed to.
I don't really care about testing Get3(). I only care that MustReturn3() will follow the interface detail, ie, it will return 3.
So I would write a test like so:
private A _a;
[TestInitialize]
public void Initialize()
{
_a = new B();
}
[TestMethod]
public void ShouldReturn3WhenICallMustReturn3()
{
Assert.AreEqual(3, _a.MustReturn3());
}
This ensures I am not testing any implementation detail; I'm only testing what the interface tells me that the class implementation should do.
This is how I write my unit tests, actually.
You can see a real working version of a test like this here.
It makes unit testing easier as you can easily mock interfaces to return you data needed for the code your testing.

C#: How to unit test a method that relies on another method within the same class?

I have a class similar to the following:
public class MyProxy : ClientBase<IService>, IService
{
public MyProxy(String endpointConfiguration) :
base(endpointConfiguration) { }
public int DoSomething(int x)
{
int result = DoSomethingToX(x); //This passes unit testing
int result2 = ((IService)this).DoWork(x)
//do I have to extract this part into a separate method just
//to test it even though it's only a couple of lines?
//Do something on result2
int result3 = result2 ...
return result3;
}
int IService.DoWork(int x)
{
return base.Channel.DoWork(x);
}
}
The problem lies in the fact that when testing I don't know how to mock the result2 item without extracting the part that gets result3 using result2 into a separate method. And, because it is unit testing I don't want to go that deep as to test what result2 comes back as... I'd rather mock the data somehow... like, be able to call the function and replace just that one call.
Do you have a preference for mocking frameworks?
The Partial Mock feature in Rhino Mocks seems like it should do what you want.
You can't really do that. You have three choices:
Subclass MyProxy and override DoWork, which will require some fiddling to please the compiler
Mock the Channel property, which will require that it is settable in the base class
Move DoWork out into another class, pass it the Channel in the constructor, and mock that in your tests
Do the following:
Set up an IService property such as:
public IService MyService { get; set; }
Then you can do: int result2 = MyService.DoWork(x) as long as somewhere in the constructor or whatever you set MyService = this;
If you don't want to expose the property you can make it private or whatever and test it using accessors.
You can do it by using latest Microsoft Research project Moles
Once you get it running, you can do following
MMyProxy.DoWork32 = () => put your mock result here.
Remember to set moleBehavior to fall-through for the unmocked methods.
I believe that you have a design issue here, your IService.DoWork should most likely live in another class, it looks like just a thin wrapper on something else. Have you considered refactoring it?
Then if it lives in another class you don't need any special handling for mocking.

NUnit Mocking not working for Singleton Method

Bear with me, I'm new to NUnit. I come from the land of Rails, so some of this is new to me.
I have a line of code that looks like this:
var code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
I'm trying to mock it, like this (assume code is already initialized):
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
When I debug the test, getCodeByCodeNameAndType is returning null, instead of the expected code. What am I doing wrong?
NUnit version: 2.2.8
I'm sorry, but I've never used NUnit.Mocks - but I do have some experience with NMock and Moq [which, by the way, I highly recommend]. Typically, you use a mocking library to generate proxies for Interface definitions, and I presume NUnit.Mocks operates the same way.
Therefore, if you would like to mock your singleton, you will likely have to do the following,
a. Create an interface, say
// All methods you would like to mock from this class, should
// be members of this interface
public interface IWebSiteConfiguration
{
// Should match signature of method you are mocking
CodeType getCodeByCodeNameAndType (
string codeString,
CatalogType catalogType);
}
b. "Implement" interface
// You've already written the method, interface matches signature,
// should be as easy as slapping interface on class declaration
public class WebSiteConfiguration : IWebSiteConfiguration { }
c. Consume interface
alright, so step c. is where most of your work will be. Logically, if you are mocking your singleton, you are actually unit testing the consumer [which you have left out of your sample]. For c. simply add a parameter to the consumer's ctor, or add a publicly accessible property of Type 'IWebSiteConfiguration', and then internally, reference the instance member and invoke your methods against this new interface. Consider this,
was
public class MyClass
{
public MyClass () { }
public void DoSomething ()
{
// bad singleton! bad boy! static references are bad! you
// can't change them! convenient but bad!
code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType (
"some.string",
someCatalog)
}
}
becomes
public class MyClass
{
private readonly IWebSiteConfiguration _config = null;
// just so you don't break any other code, you can default
// to your static singleton on a default ctor
public MyClass () : this (WebSiteConfiguration.Instance) { }
// new constructor permits you to swap in any implementation
// including your mock!
public MyClass (IWebSiteConfiguration config)
{
_config = config;
}
public void DoSomething ()
{
// huzzah!
code = _config.getCodeByCodeNameAndType ("some.string", someCatalog)
}
}
In your unit test, create the mock, pass a reference of the mock to the consumer, and test the consumer.
[Test]
public void Test ()
{
IWebSiteConfiguration mockConfig = null;
// setup mock instance and expectation via
// NUnit.Mocks, NMock, or Moq
MyClass myClass = new MyClass (mockConfig);
myClass.DoSomething ();
// verify results
}
This also serves as a practical introduction to Dependency Injection [DI]. It's simply the practice of passing, or "injecting", references of services [eg your web site configuration class] to the consumer, rather than having the consumer invoke the service directly [eg via static singleton class].
Hope this helps :)
A DynamicMock creates a new object in-memory that represents the interface, or marshallable (inherits from MarshalByRef) class you want to mock.
Try this:
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
WebSiteConfiguration conf = (WebSiteConfiguration)_websiteConfigurationMock.MockInstance;
var x = conf.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
Note that the third line there will not work unless WebSiteConfiguration inherits from MarshalByRef.
What you typically do is mock an interface and get a new object that implements this interface, but behaves the way you've configured it to do, without having to go and make a concrete type for it, so I'm not entirely sure what you're doing is going to work unless you employ a better isolation framework, like TypeMock that can intercept calls to static methods/properties in existing objects.
Seems there is a kind of solution for this using reflection, or maybe I totally misunderstood this.
It is discussed here:
http://www.geekbeing.com/2010/05/23/how-to-unit-test-singleton-hack-in-c
Could it really works?
public class TestableSingleton : SingletonClass
{
public TestableSingleton ()
{
FieldInfo fieldInfo = typeof(SingletonClass)
.GetField("_instance",
BindingFlags.Static | BindingFlags.NonPublic);
fieldInfo.SetValue(Instance, this);
}
}
Project availabe on https://github.com/rbabreu/TestableSingleton
Actually I could not compile it on Visual Studio since the SingletonClass would have a private constructor. If someone get it to work would be great to avoid the overhead of adapter pattern.

Categories