Mocking internal classes with Moq for unit testing - unit-testing

Say I have a class "ClassA", which has a dependency on a class "ClassB" (injected into the constructor of ClassA). I want to mock ClassB so that I can test ClassA in isolation. Both classes are internal.
Correct me if I'm wrong but it looks like Moq can only mock a class if it is public, it has a public parameterless constructor, and the methods to be mocked are public virtual. I don't really want to make these classes publicly visible. Am I missing something with Moq, or is it just not suitable for what I want to do?
I guess I could create an interface (say "IClassB") that ClassB implements, inject that into ClassA, and mock the interface instead. ClassB can still be internal (although I realise the interface methods would have to be public). While this would work, I feel uneasy about creating lots of interfaces, whose only purpose is to support unit test mocking. Thoughts?

You could make internals visible to Moq by adding InternalsVisibleToAttribute in your project's assembly.cs, like this:
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
Why "DynamicProxyGenAssembly2" and not "Moq"? It's the name of dynamic assembly created to contain dynamically generated proxy types (all of this is handled by yet another library, Castle's DynamicProxy) which is used by Moq. So you expose types to dynamic proxy assembly, not to Moq itself.
But, what's the point of mocking class if there's no overridable member? You won't mock anything and all calls will use actual implementation. Your second solution,
I guess I could create an interface (say "IClassB") that ClassB implements, inject that into ClassA, and mock the interface instead.
is what I would normally do. Its purpose is much more than "to support unit test mocking" - it helps you build losely coupled components, which is always something worth aiming for.

Also, you can add this into .csporj file.
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>DynamicProxyGenAssembly2</_Parameter1>
</AssemblyAttribute>
</ItemGroup>

Related

Testing a unit for which a specific private method invocation is required?

I have a testing dilemma:
I'm writing a unit test for Unit A. The method I'm about to test is func(B param). In the (non testing) code the only place where the func(..) is called is in class C, it's also the only place in the project where variables of type B can be instanciated (to be sent as parameters to the func(B param), so the instanciation method is private.
Now, I'm not sure how should I create a B instance inside the Unit test.
Of cause I can change private to public in a method declaration of the method which creates B, but I don't feel right about it, since it'll expose the method to the rest of the project.
I can also simply duplicate the B creation method into the Unit test class, but I hate duplicating code.
Is there some known best practice for such cases?
Thanks a lot,
Dima
You would be looking into using a mocking framework like EasyMock or Mokito to create a "test double" object of your class B here.
As a rule of thumb, only public methods should be tested directly. By extension, public code should test all private code. Depending on what language you're using, you can also force less exposed code to be exposed to unit testing frameworks without having to change every method (e.g. InternalsVisibleTo in C#) but I accept that this option won't be available to all languages using all frameworks.
As well as unit testing, another tool in your armoury should be some sort of code coverage tool to ensure that as much of your code is being covered by said tests as possible.

Unit Test, Should you subclass the class you're testing?

I am starting TDD both at work and at home (I know I'm late to the party). I already have several tests for public methods for classes. However many of the classes I write have lots of protected functions. When creating a test class, should I have it subclass the class to be tested so I can have coverage on the protected methods?
Thanks,
Jec
In an ideal world, you wouldn't need to test the protected methods directly, instead you would only be testing through the public interface. However, of course the world isn't ideal, and I don't think it's a bad thing to be testing protected methods if there is a good reason to.
I think whether to sub-class or not depends on the nature of the protected methods:
If they are abstract or blank methods designed to be overridden by a sub-class, and you want to test that the methods are being called, then a testing sub-class is a good way to do this, as you can use the sub-class as a way to intercept these method calls and verify how they were called etc. One thing I would say is to be careful that any logic in a testing sub-class is purely for the purpose of verifying method calls, otherwise you could introduce behavior which may impact your tests negatively (for example, you could easily add logic to a testing sub-class which causes a given test to pass based only on the logic in your testing sub-class, and not the logic in the real implementation).
If they are methods in a class designed to expose functionality to sub-classes, then I don't think that you need to sub-class the class under test. Because the methods are protected scope, different classes in the same package can access them, and therefore all you need to do is have your tests in the same package to call these methods to test them (which in my book is generally good practice, the tests should be in the same package but stored in a different directory).
Welcome. It's never too late for the party!
Creating sub-classes to get access to private or protected methods is perhaps the best way. It creates the maximum "surface" for you to construct your tests.
In other situations, I have created sub-classes to allow me to instrument a class under test, to add factory and singleton patterns to a class under test, and to help allow substitutions of mock objects.
You can subclass the class to test its protected interface.
Or you can let a mocking library do the subclassing. Depending on what the protected interface does, that may be preferable.
Specifically, if the base class uses the template method pattern, creating the subclass as a mock is probably better. If the base class just offers helper functions for the derived classes to use, consider putting them into a separate class and making them public.
You should test public interface of your class.
So you don't need to write unit test for private or protected members.
Your private and protected members are called inside public members so when you test your public members all private and protected members will be tested implicitly as well.
Many would argue that you should only test the public methods of a class.
Subclassing would work for protected properties and methods but would not work for private, internal, etc.
Depending on what language you use you can declare the test class and the class that it tests to be "friends" so the test class can see the other class' properties.

Static Methods As A Wrapper

If you have a class called MyClass with a set of public methods; MethodA, MethodB and MethodC. And in some locations of an application you only need a single method from MyClass, for example:
MyClass myClass = new MyClass();
myClass.MethodA();
To simplify the above I would like to create a single static method that wraps the above lines of coded. I am planning to write unit tests against MethodA. In my unit test MethodA interacts with an interface that is implemented using a mock framework (I think this is called Inversion of Control).
Is it safe to assume that by testing MethodA that the static method (wrapper method) is also being tested indirectly. I am assuming the actually implementation for the interface used in MethodA is also being tested.
Or should I not implemented the static method?
Please, don't do that!
Static methods used like you want to do are the exact opposite of inversion of control / dependency injection, and as such, are a bad practice.
What you want to do is inject into all classes that need a MyClass an interface to it (either injected through the constructor or a setter, manually or using a IoC framework like Spring).
If you wrap your lines of code in a static method that you call from another class, then you'll couple the specific implementation of MyClass too tightly, which is the opposite of what you want to achieve.
But to answer your more specific question, it's never safe to assume the code is tested by another test, unless it actually is. What I mean is: if there is NO test that go through the static method, then it's not covered. Even if you may think it's trivial, don't forget it may be refactored later, and no test will indicate it's broken.
No, it's not safe to assume the wrapper method is also being tested. There is code in the wrapper method, and that code could have a defect in it, so you'll need to write unit tests against that code as well.

Can I get away with not mocking all methods in an interface in C++ when using googlemock

I am using Google Mock 1.6 RC and am trying to Mock a COM Interface. There are close to 50 methods in the COM Interface some of which are inherited from base interfaces. When I create a mock struct that inherits from this interface and mock only the methods I am using, I get the cannot instantiate abstract class error.
I want to know if it is possible to do this in googlemock or not.
It is not possible to do. You have to overload all pure virtual methods from all interfaces (except for the constructor and destructor).
You have to override every method that has been declared as pure virtual in the classes you inherit from, directly or indirectly. There are two reasons not to want override them all:
There are too many of them and you have something better to do with your time than to go over them all.
Compiling a mock class with all of them mocked out is too slow and takes too much memory.
The fix for (1) is to use the gmock_gen.py script in Google Mock's scripts directory. It goes over the class definition and converts method declarations into the MOCK_METHOD statements. If you have problems with (2), you can replace the unnecessary MOCK_METHOD statements with stubs:
MOCK_METHOD1(f, bool(int i));
with
virtual bool f(int i) {
thrown std::exception("The stub for f(int) has been invoked unexpectedly.");
}
Throwing an exception will alert you to a situation where a particular stub has been invoked, meaning you likely need to mock it instead.
Edit: If the original interfaces to mock are written using Microsoft's macros, this thread has a script posted that converts them to C++ acceptable to gmock_gen.py.
I'm not entirely sure whether all methods should be covered in the mock class... In the gmock examples you can see that for example destructors are not mocked. Therefore I presume there is no need to mock the entire class.
Anyway, shouldn't you create mock class rather than mock struct?
However, there is a gmock_gen.py tool in scripts/generator that should do the hard work of mocking large classes for you.

For me to use Moq, do all my classes have to implement an interface?

I want to use Moq, but I am using Nhibernate and I didn't create interfaces for all my Model classes (POCO classes).
Do I have to create an interface for each class for me to be able to moq my POCO classes?
You can mock virtual methods, but its best if you use an interface.
Reason I say this is as follows:
var mockObject = new Mock<IMyObject>();
If you use a virtual method it becomes:
var mockObject = new Mock<MyObject>(params...);
You are forced to include the parameters for concrete objects, but you obviously don't need to for interfaces. All tests using concrete classes will require updating if you decide to change the class' constructor at a later date. I've been burned by this in a past so try not to use virtual methods for testing anymore.
I should add that by attempting to mock concrete types you are defeating the purpose of mocking frameworks. You should be mocking roles, not types. Therefore working to an abstraction, in this case an interface is a great thing to do.
Another reason is how interfaces work, interfaces state a contract but not behavior. They should be used when you have multiple implementations, and I class testing as a behavior hence the valid reason to introduce a new interface.
The classes/methods you are Mocking either need to implement an interface or be virtual. You can test any class/method as long as its accessible, but there's no way to mock something that cannot be overridden or implemented explicitly.