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.
Related
If i need to test if a method within class under test has been called or not, can it be done without Mockito (or any mocking tool for that matter)?
Reason asking is that wherever i read about Mockito and similar tools, it says one should never mock CUT but its dependencies (that part is clear).
So, if thats the case then there are only 2 options left:
there is some other way of testing it without mocking
or
the fact the method was called should not be tested itself but some side effect or methods return value
For example (trivial and non-realworld), class MyClass can have 2 methods: A() and B(). A conditionay calls B based on some internal state.
After arranging state & acting by calling A() we want to assert that B() was called.
Either its not possible without mocking the whole CUT or 2 methods like this in a single class are always SRP violation smell and call for redesign where B() should actually be (mocked) dependency of MyClass CUT.
So, whats correct?
Usually I tend to not even use spies, instead I prefer to write my code in a way that for any class I write:
I test only non-private methods, since they're entry points into the class under test. So, in your example, if a() calls b(), maybe b() should be be private and, as a consequence, should not be tested. To generalize, a() is something that a class "can do" (a behavior), so I test the behavior, and not the method itself. If this behavior internally calls other things - well, its an internal matter of that class, if possible I don't make any assumptions on how does the class work internally, and always prefer "white-box" testing.
I only test "one" non-private method in a test.
All the methods should return something (best option) or at least call dependencies, or change internal state of the object under test. The list of dependencies is always clean-to-understand, I can't instantiate the object of CUT without supplying it a list of dependencies. For example, using constructor dependency injection is a good way of doing this. I mock only dependencies indeed, and never mock / spy CUT. Dependencies are never static but injected.
Now with these simple rules, the need to "test if a method within class under test has been called or not" basically can boil down to one of the following:
you're talking about private method. In this case - don't test it, test only public things.
The method is public - in this case you explicitly call it in unit test, so its irrelevant.
Now lets ask why do you want to test this if a method within CUT has been called or not?
If you want to make sure that it changed something. If this "something" is within the class - in other words, its internal state has changed, check in test that the change is indeed done in the state by calling another method that allows to query the state
If this "something" is a code that is managed by dependency, create a mock of this dependency and verify that it was called with the expected parameters.
Take a look at the Mockito Documentation (https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/Mockito.html#13)
When using a Spy you can 'replace' a method in the same class that is under test.
#ExtendWith(MockitoExtension.class)
public class Test {
class MyClass {
public void a() {
b();
}
public void b() {
}
}
#Test
public void test() {
MyClass testClass = new MyClass();
MyClass spy = Mockito.spy(testClass);
Mockito.doNothing().when(spy).b();
spy.a();
Mockito.verify(spy, Mockito.times(1)).b();
}
}
So whether that is something that should be done is a different question ;)
I think it highly depends on what method B() is actually doing and whether that is supposed be part of MyClass in the first place.
Either its not possible without mocking the whole CUT
In this case we do not mock the whole CUT only the method you do not want to be called.
Reason asking is that wherever i read about Mockito and similar tools, it says one should never mock CUT but its dependencies (that part is clear).
I believe this statement is not entirely accurate in correlation with spying.
The whole point of spying in my eyes is to use it on the class under test. Why would one want to spy on a dependecy that is not even supposed to be part of the test in the first place?
Suppose we have a class like this :-
class A {
internal val obj : Obj
get() = Application.getbean(Obj::class)
fun method1(){
val result = obj.somefunc()
..../code/
}
fun method2(){
...../code/
}
}
I wan't to write unit test using the junit mockito framework to test the functionality of method1 and wan't to mock obj object . In some other threads on stackoverflow people has suggested to use constructor dependency injected but that is not possible in my case because of the issue of circular dependency . In some other answers people has suggested to move this object instantiation inside the method ,but i don't want to go that way .Is there any way to mock this obj object.
It's very hard to unit test code, that is written in a non-testable way. That is why you should inject dependencies and not to hold them, that is why you should obtain objects and not to create them by yourself. If you're assume that your code might be tested, always think how first.
In your case it's a bit difficult to mock Obj, but not impossible since the actual creation (constructor calling) of the object is done with a different class (not the one being tested).
In your example you're using static method, maybe you can mock it's behavior with a PowerMockito? Please take a look at this answer.
Other than that, I just can suggest to change the code.
To inject object creating class as a dependency or use some other approaches, which might involve some architectural changes.
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.
I have a constructor and a property in the class:
private IMyCollectionObjects _myCollectionObjects;
public MyClassConstructor(string message)
{
_myCollectionObjects = MyCollection.GetCollectionObejects(message);
}
With as much detail can you please help me understand how to unit test this constructor
and GetCollectionObjects method?
How do I completely decouple the
classes? You can give the answer
using any IoC, I want to
understand the concept.
Thank you.
Dependencies on static members such as GetCollectionObjects are difficult to test because you can't replace its implementation at runtime. This means that you cannot fully isolate an instance of MyClassConstructor from the implementation details of GetCollectionObjects. Without isolation of the test target, it can't really be considered a unit test.
See here for further discussion of static dependencies.
You can refactor this code to be fully decoupled (and thus fully testable):
private readonly IMyCollectionObjects _myCollectionObjects;
public MyClassConstructor(IMyCollectionObjects myCollectionObjects)
{
_myCollectionObjects = myCollectionObjects;
}
This bubbles the knowledge of how to turn a message into a collection right out of MyClassConstructor, making the class simpler, more cohesive, and less coupled.
For of all, unit testing is all about unitary testing, that is, one thing at a time.
With as much detail can you please help me understand how to unit test this constructor and GetCollectionObjects method?
First things first, have you unit tested your MyCollection class?
If not, you should begin with it, as your MyClassConstructor class depends on it, that is the basis of dependency injection. Otherwise, how can you manage to know if the results you're getting are right or wrong? You won't be able to test and be sure that it works flawlessly.
How do I completely decouple the classes? You can give the answer using any IoC, I want to understand the concept.
I my humble point of view, you must have a clear reason to make an object dependant of another using dependency injection. Once you make an object depend on another, it makes no sense, in my opinion, to decouple them. One way of decoupling might be to use Unity Application Block of Enterprise Library.
Unit test this constructor
You generally only need to check for three things while testing such a constructor.
That the constructor doesn't return a null value;
That the instance it returns is of the expected type;
That the object you expect to be instantiated through its dependency is actually instiated.
[TestCase("message")]
public void DependentConstructorTest(string message) {
MyClassConstructor myclass = new MyClassConstructor(message);
Assert.IsNotNull(myclass);
Assert.IsInstanceOf(typeof(MyClassConstructor), myclass);
Assert.IsNotNull(myclass.MyCollection); // Where MyCollection represents the property that
// exposes the instance created of the object from
// which your MyClassConstructor class depends on.
}
Note: This test is written using NUnit attributes and assertion methods. Use whatever else you like.
Here is roughly what you would need to do (with some assumptions).
Assuming MyCollection is a static class and GetCollectionObjects parses a string and returns an IMyCollectionObjects, you would first need to make MyCollection non-static, and pass it through the constructor as well. Static classes/methods used in a class create a tight coupling, more or less by definition.
Now you would be constructing the class passing a message string and a MyCollection. Your constructor uses the two in combination to populate a member variable of type IMyCollectionObjects. In order to ensure that this happens as expected, you will need a way to examine the result from outside the class (i.e. a public method). So you will need a property getter that exposes _myCollectionObjects.
Now you just need to call this contructor from one or more tests, and check the property after construction to ensure parsing the string into a collection was successful.
Note that this is really more of an integration test than a discrete unit test. You are really testing that the parsing was successful. If the class represented here is really what you intend to test, the test would really just be checking that GetCollectionObjects was called. The result of that call is really irrelevant, because you would (presumably) have a separate test or set of tests that ensure that the method GetCollectionObjects on MyCollection works as expected.
I have a code base where many of the classes I implement derive from classes that are provided by other divisions of my company. Working with these other devisions often have the working relationship as though they are third party middle ware vendors.
I'm trying to write test code without modifying these base classes. However, there are issues with creating meaningful test
objects due to the lack of interfaces:
//ACommonClass.h
#include "globalthermonuclearwar.h" //which contains deep #include dependencies...
#include "tictactoe.h" //...and need to exist at compile time to get into test...
class Something //which may or may not inherit from another class similar to this...
{
public:
virtual void fxn1(void); //which often calls into many other classes, similar to this
//...
int data1; //will be the only thing I can test against, but is often meaningless without fxn1 implemented
//...
};
I'd normally extract an interface and work from there, but as these are "Third Party", I can't commit these changes.
Currently, I've created a separate file that holds fake implementations for functions that are defined in the third-party supplied base class headers on a need to know basis, as has been described in the book "Working with Legacy Code".
My plan was to continue to use these definitions and provide alternative test implementations for each third party class that I needed:
//SomethingRequiredImplementations.cpp
#include "ACommonClass.h"
void CGlobalThermoNuclearWar::Simulate(void) {}; // fake this and all other required functions...
// fake implementations for otherwise undefined functions in globalthermonuclearwar.h's #include files...
void Something::fxn1(void) { data1 = blah(); } //test specific functionality.
But before I start doing that I was wondering if any one has tried providing actual objects on a code base similar to mine, which would allow creating new test specific classes to use in place of actual third-party classes.
Note all code bases in question are written in C++.
Mock objects are suitable for this kind of task. They allow you to simulate the existence of other components without needing them to be present. You simply define the expected input and output in your tests.
Google have a good mocking framework for C++.
I'm running into a very similar problem at the moment. I don't want to add a bunch of interfaces that are only there for the purpose of testing, so I can't use any of the existing mock object libraries. To get around this I do the same thing, creating a different file with fake implementations, and having my tests link the fake behaviour, and production code links the real behaviour.
What I wish I could do at this point, is take the internals of another mock framework, and use it inside my fake objects. It would look a little something like this:
Production.h
class ConcreteProductionClass { // regular everyday class
protected:
ConcreteProductionClass(); // I've found the 0 arg constructor useful
public:
void regularFunction(); // regular function that I want to mock
}
Mock.h
class MockProductionClass
: public ConcreteProductionClass
, public ClassThatLetsMeSetExpectations
{
friend class ConcreteProductionClass;
MockTypes membersNeededToSetExpectations;
public:
MockClass() : ConcreteProductionClass() {}
}
ConcreteProductionClass::regularFunction() {
membersNeededToSetExpectations.PassOrFailTheTest();
}
ProductionCode.cpp
void doSomething(ConcreteProductionClass c) {
c.regularFunction();
}
Test.cpp
TEST(myTest) {
MockProductionClass m;
m.SetExpectationsAndReturnValues();
doSomething(m);
ASSERT(m.verify());
}
The most painful part of all this is that the other mock frameworks are so close to this, but don't do it exactly, and the macros are so convoluted that it's not trivial to adapt them. I've begun looking into this on my spare time, but it's not moving along very quickly. Even if I got my method working the way I want, and had the expectation setting code in place, this method still has a couple drawbacks, one of them being that your build commands can get to be kind of long if you have to link against a lot of .o files rather than one .a, but that's manageable. It's also impossible to fall through to the default implementation, since we're not linking it. Anyway, I know this doesn't answer the question, or really even tell you anything you don't already know, but it shows how close the C++ community is to being able to mock classes that don't have a pure virtual interface.
You might want to consider mocking instead of faking as a potential solution. In some cases you may need to write wrapper classes that are mockable if the original classes aren't. I've done this with framework classes in C#/.Net, but not C++ so YMMV.
If I have a class that I need under test that derives from something I can't (or don't want to) run under test I'll:
Make a new logic-only class.
Move the code-i-wanna-test to the logic class.
Use an interface to talk back to the real class to interact with the base class and/or things I can't or won't put in the logic.
Define a test class using that same interface. This test class could have nothing but noops or fancy code that simulates the real classes.
If I have a class that I just need to use in testing, but using the real class is a problem (dependencies or unwanted behaviors):
I'll define a new interface that looks like all of the public methods I need to call.
I'll create a mock version of the object that supports that interface for testing.
I'll create another class that is constructed with a "real" version of that class. It also supports that interface. All interface calls a forwarded to the real object methods.
I'll only do this for methods I actually call - not ALL the public methods. I'll add to these classes as I write more tests.
For example, I wrap MFC's GDI classes like this to test Windows GDI drawing code. Templates can make some of this easier - but we often end up not doing that for various technical reasons (stuff with Windows DLL class exporting...).
I'm sure all this is in Feather's Working with Legacy Code book - and what I'm describing has actual terms. Just don't make me pull the book off the shelf...
One thing you did not indicate in your question is the reason why your classes derive from base classes from the other division. Is the relationship really a IS-A relationshiop ?
Unless your classes needs to be used by a framework, you could consider favoring delegation over inheritance. Then you can use dependency injection to provide your class with a mock of their class in the unit tests.
Otherwise, an idea would be to write a script to extract and create the interface your need from the header they provide, and integrate this to the compilation process so your unit test can ve checked in.