I have a class say A like mentioned below :
class A
{
void show()
{}
int data(int x)
{}
.....
};
I need to mock the class - since the member functions are not virtual - can I design my mock class like mentioned below:
class MockA : public A
{
MOCK_METHIOD0(show, void ());
MOCK_METHIOD1(data, int (int));
}
Can I implement this way and is there a chance from MockA to miss out mocking of
any function of class A?
Objects created using MockA will ever anyway land up calling class A actual method implementation?
Generally for this case you do not have the mock inherit from A and instead use a compile time mechanism to select whether to use an implementation class or a mock class. E.g. templating everything that uses A and then instantiating the templates with either A or MockA, to replace the production class with the mock one in the testing setup. Any methods that are not implemented in the mock, but which are called, result in a compile time error. The use of the macros in the mock definition are pretty much the same even though the methods are non-virtual.
The hard part is replacing the class everywhere. Templates, referencing the class name via a macro, or using the same class name and making sure only one is linked are all possibilities.
Related
I am writing a GMOCK test cases for a class:
class A{ .. void Text() .. };
Now one of the member method of class A has an class B type object embedded into it and also refers to static member methods:
void A::Text()
{
B bobj;
B::SMethod();
bobj->BMethod();
......
}
In such a case how can I mock B and its methods?
Instead of testing A, you can test a class derived from it, let's call it TestableA. In A make Text() virtual and in override use mock of the B. Also, have a look at this question for more ideas of how to mock classes with static methods.
Nevertheless, the best solution would be to break existing tight dependency between A and B by introducing an interface (e.g. InterfaceB) and injecting it into Text(). SMethod() would become a (non-static) member of the interface. In production you'd be injecting ActualB where ActualB::SMethod() calls static B::SMethod(). In tests you'd use MockB::SMethod(), tailored by test needs.
I have abstract class which has few implemented protected methods and few abstract methods.
I am trying to write some tests for the protected methods.
Since these are not available even in the extended classes to outside world, I would like to create anonymous Test class which can extend and verify/mock my stuff.
export abstract class AbsClass implements AbsInterface {
protected extract(filter: string) {
//some implemented code to test
}
abstract someMethod();
}
I am not able to figure out how to create something like this anonymously
export class TestClass extends AbsClass {
public testExtract(){
//call super.extract and verify result
}
}
I've run into this before. It seems like the export/abstract keywords interfere with each other. I've had to define the class and then export on a separate line to get around this.
Example:
abstract class BaseClass {}
export default BaseClass
There are some workarounds discussed in this related issue. See also:
https://github.com/microsoft/TypeScript/issues/36060
https://github.com/microsoft/TypeScript/issues/17293
https://github.com/microsoft/TypeScript/issues/35822
The short answer is that it's very difficult to represent anonymous classes that access private/protected members of their superclass right now. If you're just trying to test parts of the superclass, does the implementing class really have to be anonymous?
(As an aside: I'm still pretty new at testing generally, but I've seen a lot of strongly worded advice about not explicitly testing private/protected methods. Would it be preferable to test the public API methods that call the private/protected ones instead?)
I've a case in which I need to add some functions to a game engine class I'm using for a VR project without overriding the class it self:
The engine class name is AnnwaynPlayer that contains many useful methods to control the player, now I'm in the networking phase so I need to add 2 extra methods to this lib class which are setActive() and setConnected(), what is the best way to do this ?
If you can't touch the class itself then you probably want to use inheritance. This is one of the main goals of object-oriented programming -- to be able to add/change the behavior of an existing class without altering it. So you want something like:
class MyAnnwaynPlayer : public AnnwaynPlayer {
public:
void setActive();
void setConnected();
// ...
}
Now, things will be fine if AnnwaynPlayer has a virtual destructor. If it doesn't and your MyAnnwaynPlayer class has a non-trivial destructor then you have to wary of using an instance of MyAnnwaynPlayer through a pointer (be it raw or smart) of base class AnnwaynPlayer. When a pointer of the type is deleted, it will not chain through a call to your MyAnnwaynPlayer destructor.
Also consider ADL if you only need access to the public API of the base class. It's safer than inheritance, because you don't necessarily know the right class to inherit from in cases where the implementation returns something ultimately unspecified (like an internal derived class).
In essence, this would look like this:
namespace AnnwaynNamespace {
void setActive(AnnwaynPlayer& p);
void setConnected(AnnwaynPlayer& p);
};
And you could call them without using those functions (or the namespace), because ADL.
void wherever(AnnwaynNamespace::AnnwaynPlayer& p) {
setActive(p);
}
So setActive, etc, become part of the actual public API of the class, without involving any inheritance.
I've got a class that inherits from another class like so:
class TestClass : public BaseClass
I am wondering if it is possible to make this a test class using the TEST_CLASS macro or some other macro that is part of the Microsoft Unit Testing Framework for C++. I tried:
class TEST_CLASS(TestClass : public BaseClass)
But the IDE gives the error 'Error: expected either a definition or a tag name' and the compiler error is error C3861: '__GetTestClassInfo': identifier not found
I know it's probably bad practice to inherit on a test class but it would make implementing the test easier. I am relatively new to C++ so I am wondering if it is something simple I have missed or if it's just not possible.
Thanks,
There is one other option you didn't include and others may be tripping over this question without knowing the solution.
You can actually derive from any arbitrary type by looking at the macro itself:
///////////////////////////////////////////////////////////////////////////////////////////
// Macro to define your test class.
// Note that you can only define your test class at namespace scope,
// otherwise the compiler will raise an error.
#define TEST_CLASS(className) \
ONLY_USED_AT_NAMESPACE_SCOPE class className : public ::Microsoft::VisualStudio::CppUnitTestFramework::TestClass<className>
As C++ supports multiple inheritance you can easily derive by using code similar to the following:
class ParentClass
{
public:
ParentClass();
virtual ~ParentClass();
};
TEST_CLASS(MyTestClass), public ParentClass
{
};
Just remember that if you are working with resources you will need to have a virtual destructor to have it be called. You will also have to call the initialize & cleanup methods directly if you are going to be using them, because the static methods they create are not called automagically.
Good luck, Good testing!
It's been a while since I used CppUnitTestFramework but back then this site has been a valuable resource for many questions on that topic.
TEST_CLASS is preprocessor macro. You can use it to declare a test class like
TEST_CLASS(className)
{
TEST_METHOD(methodName)
{
// test method body
}
// and so on
}
That's it. As far as I know there is no way to inherit test classes from one another.
Maybe though composition over inheritance might help in your specific case.
Here's my issue, I'd like to mock a class that creates a thread at initialization and closes it at destruction. There's no reason for my mock class to actually create and close threads. But, to mock a class, I have inherit from it. When I create a new instance of my mock class, the base classes constructor is called, creating the thread. When my mock object is destroyed, the base classes destructor is called, attempting to close the thread.
How does one mock an RAII class without having to deal with the actual resource?
You instead make an interface that describes the type, and have both the real class and the mock class inherit from that. So if you had:
class RAIIClass {
public:
RAIIClass(Foo* f);
~RAIIClass();
bool DoOperation();
private:
...
};
You would make an interface like:
class MockableInterface {
public:
MockableInterface(Foo* f);
virtual ~MockableInterface();
virtual bool DoOperation() = 0;
};
And go from there.
First of all, it is not necessarily an unreasonable thing that your classes might be well designed for their use, but poorly designed for testing. Not everything is easy to test.
Presumably you want to use another function or class which makes use of the class which you want to mock (otherwise the solution is trivial). Lets call the former "User" and the latter "Mocked". Here are some possibilities:
Change User to use an abstract version of Mocked (you get to choose what kind of abstraction to use: inheritance, callback, templates, etc....).
Compile a different version of Mocked for your testing code (for example, #def out the RAII code when you compile your tests).
Have Mocked accept a constructor flag to turn off its behavior. I personally would avoid doing this.
Just suck up the cost of allocating the resource.
Skip the test.
The last two may be your only recourse if you can not modify User or Mocked. If you can modify User and you believe that designing your code to be testable is important, then you should explore the first option before any of the others. Note that there can be a trade off between making your code generic/flexible and keeping it simple, both of which are admirable qualities.
The pimpl idiom might suit you as well. Create your Thread class, with a concrete implementation that it brings in underneath. If you put in the right #defines and #ifdefs your implementation can change when you enable unit testing, which means that you can switch between a real implementation and a mocked one depending on what you are trying to accomplish.
One technique I've used is to use some form of decorator. Your final code has a method which creates its instance on the stack and then calls the same method, but on a member which is a pointer to your base class. When that call returns, your method returns destroying the instance you created.
At test time, you swap in a mock which doesn't create any threads, but just forwards to the method you want to test.
class Base{
protected:
Base* decorated;
public:
virtual void method(void)=0;
};
class Final: public Base{
void method(void) { Thread athread; decorated->method(); } // I expect Final to do something with athread
};
class TestBase: public Base{
void method(void) { decorated->method(); }
};