eranpeer / fakeit Goto Github PK
View Code? Open in Web Editor NEWC++ mocking made easy. A simple yet very expressive, headers only library for c++ mocking.
License: MIT License
C++ mocking made easy. A simple yet very expressive, headers only library for c++ mocking.
License: MIT License
GoogleMocks can mock non-virtual methods. Is it possible to use the same strategy with FakeIt?
Hi,
I wonder if there is a way to stub a protected virtual method using a spy object or does this library work only on public methods ?? I'm using VS2015
Thanks
It's not really an issue, but more of a wish. As a developer writing unit tests with mock objects, I want to be able to easily get prepackaged code from a dependency management, such as BiiCode, so that I can incorporate this mocking functionality without having to know any Cmake magic or handle downloading/cloning repositories.
I have an interface that has its methods all declared as __stdcall that cause compilation errors whenever I try to stub/fake them. I am using the mstest single header with Visual Studio 2015 update 3.
an example illustrating the issue. Given the following interface:
class DependencyInterface
{
public:
~DependencyInterface() {}
virtual int RegularMethod(int foo, int bar) = 0;
virtual int __stdcall StdCallMethod(int foo, int bar) = 0;
};
and the following unit test code:
When(Method(mock, RegularMethod)); // works fine
When(Method(mock, StdCallMethod)); // compile error
This will produce the following errors (there are more C2784 then I listed, looks like one for each version of the stub function).
C2672
'fakeit::Mock::stub': no matching overloaded function found
C2784
'fakeit::MockingContext<void,arglist...> fakeit::Mock::stub(R (__thiscall T::* )(arglist...) volatile const)': could not deduce template argument for 'R (__thiscall T::* )(arglist...) volatile const' from 'int (__stdcall DependencyInterface::* )(int,int)'
I would like to spy a given class to make sure one method invocation results in the invocation of some other methods. While attempting to do that, the code always segfaults. I suspect the reason is that the this
pointer seems to be different, but I don't know why. I managed to reduce the test code into the following dummy test case:
#include <gtest/gtest.h>
#include <fakeit.hpp>
using namespace fakeit;
class Dummy {
public:
virtual void method() {
printf("Method called\n");
}
virtual void callMethod() {
printf("this: %p\n", (void*)this);
this->method();
}
};
TEST(DummyTest, simpleTest) {
Dummy instance;
auto spy = Mock<Dummy>(instance);
Spy(Method(spy, method));
Spy(Method(spy, callMethod));
instance.callMethod();
spy.get().callMethod();
}
Tested with HEAD @ 15b8e35
Hi, I cannot manage to compile the attached test program, I attached the output I got from clang++ 3.7
Seems GCC/Clang have trouble with macros like When and Verify (With the others too I guess)
I suppose I did something silly, or I missed something obvious, since this is the most basic program I could write.
When compiling with clang 3.6.1 on OSX std::make_shared has a problem with the THROWS macro in the destructors of Mock.
I have also tried Linux with GCC and clang (also 3.6.1), OSX with GCC. There the compiler doesn't complain.
Removing noexcept(false) compiles, probably because it defaults to the most strict declaration (noexcept(true)) if possible.
Changing THROWS to NO_THROWS also work for me. But probably this is because I didn't use any exceptions in my project yet. I'm curious to an application.
#include <fakeit.hpp>
#include <memory>
using namespace fakeit;
using namespace std;
struct T {
int x;
T(int x) : x(x) {}
virtual int get() {return x;}
};
int main() {
shared_ptr<Mock<T>> shm= make_shared<Mock<T>>();
}
/usr/local/Cellar/llvm/3.6.1/bin/../include/c++/v1/memory:3690:7: error: exception specification of overriding function is more lax than base version
class __shared_ptr_emplace
^
/usr/local/Cellar/llvm/3.6.1/bin/../include/c++/v1/memory:4280:26: note: in instantiation of template class 'std::__1::__shared_ptr_emplacefakeit::Mock<BoolTerm, std::__1::allocatorfakeit::Mock >' requested here
::new(__hold2.get()) _CntrlBlk(__a2, std::__1::forward<_Args>(__args)...);
^
/usr/local/Cellar/llvm/3.6.1/bin/../include/c++/v1/memory:4644:29: note: in instantiation of function template specialization 'std::__1::shared_ptrfakeit::Mock::make_shared<>' requested here
return shared_ptr<_Tp>::make_shared(std::__1::forward<_Args>(__args)...);
^
idp4/tests/solver/../MockFactory.hpp:37:14: note: in instantiation of function template specialization 'std::__1::make_sharedfakeit::Mock' requested here
shared_ptr<Mock> out(make_shared<Mock>());
Hi,
I have a project with std::enable_shared_from_this<> is quite commonly inherited by multiply classes. When I trying to mock these classes, I got error saying "Can't mock a type with multiple inheritance or with non-polymorphic base class".
Is there any suggestion for this scenario?
Thanks!
In such case, the Access Violation exception is thrown at:
VTUtils.hpp:33
Environment: Windows 7
Compilers:
VS 2013 (64 bit)
as well as
gcc (i686-posix-dwarf-rev2, Built by MinGW-W64 project) 4.9.1
Need to add a mock library to my unit tests.
All of my development is c++11, so I like the looks of FakeIt, but I do use the MySQL c connector. I have database classes that use it internally, and would like to mock out the MySQL c connector library.
I'd like to avoid writing an abstract base class defining an interface to the MySQL library, with a class inheriting from it that uses the MySQL c connector, and another being a mock class. I'd prefer to be able to mock the actual MySQL c functions, so I don't leave the derived class that uses the MySQL c connector untested, admittedly it would basically be a straight passthrough.
Can FakeIt help with this, or do I need to look for another mock library or use pre-processor or linker methods for C functions?
I looked through the examples and issues, and don't see anything showing mocking c functions, but wanted to ask before I assumed it can't do it.
Hi,
I just found this project and it looks great.
Are releases still being made, or is it recommended to simply use the master branch?
Looking at the Releases page, it seems that in the past (~2015) releases were made with a few weeks or months in between, but then stopped at 2.0.2 (May 2015). And there's been 120+ commits to master since that release.
Thanks in advance for any clarification!
I have a interface like this:
struct Change {
virtual void change(uint8_t r, uint8_t g, uint8_t b) =0;
};
In a test code like
function assertChanged(Mock<Change>& mock, uint8_t v1, uint8_t v2, uint8_t v3) {
Verify(Method(mock, change).Using(v1,v2,v3));
}
TEST_CASE(...) {
Mock<Change> mock;
Change* change = &mock.get();
When(Method(mock, change)).AlwaysReturn();
change->change(1, 2, 3);
assertChanged(mock, 1, 2, 3);
}
But I get
Unexpected method invocation: unknown()
An unmocked method was invoked. All used virtual methods must be stubbed!
What am I doing wrong?
As mentioned in #10 I get a crash in my simple test with Qt's QSharedPointer. AuthModel holds the context as a QSharedPointer, too!
#0 0x685d62 in fakeit::MethodProxyCreator<void>::methodProxy(unsigned int) [..]/external/fakeit.hpp:5815:20
#1 0x685459 in void fakeit::MethodProxyCreator<void>::methodProxyX<0>() [..]/external/fakeit.hpp:5820:20
#2 0x689a89 in fakeit::VirtualTable<ActivationContext>::dtor(int) [..]/external/fakeit.hpp:5615:13
#3 0x7fc23f73049f in QScopedPointerDeleter<ActivationContext>::cleanup(ActivationContext*) [..]/QtCore/qscopedpointer.h:54:9
#4 0x7fc23f730028 in QScopedPointer<ActivationContext, QScopedPointerDeleter<ActivationContext> >::~QScopedPointer() [..]/QtCore/qscopedpointer.h:101:9
The code:
Mock<ActivationContext> context;
When(Dtor(context));
QSharedPointer<AuthModel> model(new AuthModel(&context.get()));
On Windows 10 (latest update), I have a Visual Studio 2015 native C++ unit test project and I am mocking destructors using FakeIt.
This results in access violations:
fakeit.hpp, line 5806. fakeit::MethodProxyCreator::methodProxy(unsigned int id)
where invocationHandlerCollection
is an invalid object
Here is my code:
struct SomeInterface {
virtual ~SomeInterface() {}
virtual int SomeMethod(int someArgument) = 0;
};
Mock<SomeInterface> mock;
When(Method(mock, SomeMethod)).AlwaysReturn(42);
Fake(Dtor(mock));
SomeInterface* someInterface = &mock.get();
// This next line causes access violation
delete someInterface;
I am trying to mock an external api which uses the __stdcall calling convention as shown below:
class MockMe
{
public:
virtual int __stdcall foo() = 0;
};
Mock<MockMe> mock;
When(Method(mock, foo)).Return(1);
but the compiler can't detect a matching stub method
When mocking an interface class I get the following warnings:
The following code fails to compile (tested in MSVC 2013 and GCC 4.8.4, with FakeIt from 787126e):
#include <fakeit.hpp>
using namespace fakeit;
struct foo {
virtual int bar(int&&) = 0;
};
int main()
{
Mock<foo> foo_mock;
When(Method(foo_mock,bar)).AlwaysReturn(1);
return 0;
}
Removing the second & from the argument to bar() fixes the compilation.
Given the following classes:
class A {
public:
virtual ~A() {}
template<typename T> void foo() {}
};
class B {};
The following does compile correctly:
Mock<A> a;
Fake(Method(a, foo<B>));
But when ran the test executable stops because of EXC_BAD_ACCESS:
* frame #0: 0x000000010010bea7 tests` fakeit::DynamicProxy<playercommunity::command::Command>::isBinded(unsigned int) [inlined] std::__1::shared_ptr<fakeit::Destructible>::shared_ptr(this=0x00007fff5fbfc5a8, __r=0x00000001037d17d0) + 4 at memory:4250
frame #1: 0x000000010010bea3 tests` fakeit::DynamicProxy<playercommunity::command::Command>::isBinded(unsigned int) [inlined] std::__1::shared_ptr<fakeit::Destructible>::shared_ptr(this=0x00007fff5fbfc5a8, __r=0x00000001037d17d0) + 16 at memory:4252
frame #2: 0x000000010010be93 tests` fakeit::DynamicProxy<playercommunity::command::Command>::isBinded(this=0x00007fff5fbfd668, offset=2281792) + 67 at fakeit.hpp:16449
ect... up to the line where I fake method foo. Isn't faking templated method supported? :(
Latest boost 1.59.0 removed boost::test_tools::tt_detail::check_impl(), which is used by FakeIt:
In file included from test-broadcast.cpp:13:
src/FakeIt/single_header/boost/fakeit.hpp:1123:45: error: no member named 'check_impl' in namespace
'boost::test_tools::tt_detail'; did you mean 'check_type'?
::boost::test_tools::tt_detail::check_impl(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
Test case is followed, the call to spied method would create the lambda infinitely (on Mac 10.11, Xcode 7.3.1).
Mock purpose is simple, while calling the actual method, still want to verify it's get called.
using namespace fakeit;
using namespace std;
class Dumb
{
public:
virtual
void print()
{
std::cout << "Dumb" << std::endl;
}
};
TEST(MockTests, SpyStubbedMethod)
{
vector<Dumb> dumbs(10);
Dumb& dumb = dumbs[0];
Mock<Dumb> spy(dumb);
auto mock = [&]() -> void
{
std::cout << "Spy!" << std::endl;
return dumb.print();
};
When(Method(spy, print)).Do(mock);
spy.get().print();
Verify(Method(spy, print));
}
The above test case would result in infinite call inside the lambda (the lambda seems been created infinitely), however, if the dumb
is not an object in vector, it won't have any problem, work as expected, like the following case:
TEST(MockTests, SpyStubbedMethod)
{
Dumb dumb;
Mock<Dumb> spy(dumb);
auto mock = [&]() -> void
{
std::cout << "Spy!" << std::endl;
return dumb.print();
};
When(Method(spy, print)).Do(mock);
spy.get().print();
Verify(Method(spy, print));
}
And last one (for now) -
Is it possible to have Verify() (or Verify().Once() etc.) to be convertible to bool?
I have cases where I want to know programatically in the test whether the condition is true.
Thanks.
I've been looking for how to do verification of calls that check more complex argument types/values.
I saw in #68 that @reneme used Verify
with Matching
:
Verify(Method(mock, bar).Matching([](QString val){return val == "foo";}).Exactly(2_Times):
Does that exist in FakeIt? I've tried to do the same but the Matching lambda doesn't seem to get called... just need to check if I've set it up wrong or that's not actually part of FakeIt.
Context: Using FakeIt 2.0.2 single file header + 'catch'
Hello,
We have interfaces with methods that take parameters by reference.
Stubing such methods seem to work but when trying to Verify invocations, I got troubles.
struct SomeInterface {
virtual ~SomeInterface() {}
virtual int foo(int&) = 0;
};
TEST_CASE("FakeIt integration", "[fakeit]") {
Mock<SomeInterface> mock;
When(Method(mock, foo)).AlwaysDo([](int& i)
{
std::cout << i << std::endl;
return 1;
});
auto &si = mock.get();
SECTION("We mock a method with param passed by reference") {
auto i = 0;
REQUIRE(si.foo(i) == 1);
++i;
REQUIRE(si.foo(i) == 1);
Verify(Method(mock, foo).Using(0), Method(mock, foo).Using(1)).Once();
}
}
I got the following output:
0
1
...
... some lines related to Catch output
...
Verification error
Expected pattern: mock.foo(0) ... mock.foo(1)
Expected matches: exactly 1
Actual matches : 0
Actual sequence : total of 2 actual invocations:
mock.foo(1)
mock.foo(1)
All the invocations seem to be done with last value of the parameter.
Is there a way to indicate to FakeIt that this parameter should be treated as by copy. Here we only pass it by reference for optimization purpose.
Thanks for your help
Sincerely
Bertrand
How should I stub methods, that return unique_ptr<T>
?
If I try it straightforward way, the code will not compile:
class Product{};
class IFactory{
public:
virtual std::unique_ptr<Product>Create() = 0;
};
TEST_CLASS(UnitTest)
{
public:
TEST_METHOD(TestMethod1)
{
Mock<IFactory> factory;
When(Method(factory, Create)).Return(std::make_unique<Product>());
auto a = factory.get().Create();
Verify(Method(factory, Create)).Once();
}
};
error C2280: 'std::unique_ptr<Product,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function.
Seems like the error is caused by an inavailability of copy-constructor. std::shared_ptr version is obviously working fine.
I also have tried partially implementing IFactory to no result:
class IFactoryMock : public IFactory{
public:
virtual Product* CreateRaw() = 0;
std::unique_ptr<Product> Create(){
return std::unique_ptr<Product>(CreateRaw());
}
};
TEST_CLASS(UnitTest)
{
public:
TEST_METHOD(TestMethod2)
{
Mock<IFactoryMock> factory;
When(Method(factory, CreateRaw)).Return(new Product());
auto a = factory.get().Create();
Verify(Method(factory, CreateRaw)).Once();
}
};
Result Message: Assert failed. Unexpected method invocation: unknown()
An unmocked method was invoked. All used virtual methods must be stubbed!
I am getting C2766: explicit specialization; 'fakeit::DefaultValue<char16_t,void>' has already been defined while trying to build the project. Any idea what could be causing this?
First congratulations for the nice work with this lib! I'm coming from GMock and loving it!
But, I'm having some trouble with code that I don't see wgy it should no work. So, is the following supposed the work? https://gist.github.com/rafamanzo/196e2d373f2e26ea9fe3
Because I'm getting the following:
unknown location(0): fatal error: in "test_call": std::string: Unexpected method invocation: friend_mock.call(?)
Could not find Any recorded behavior to support this method call.
/home/manzo/workspace/test/test.cpp(68): last checkpoint: "test_call" entry.
I'm sorry if it is a silly mistake, but I'm on it for hours in a much larger code. After trying everyting I've written this smaller example above to reproduce my issue.
If its not a mistake made by me, I'm afraid it may somehow be related to my environment versions:
Boost 1.60.0
GCC 5.3.0
glibc 2.22
(Arch Linux)
Thanks in advance and I appreciate any response.
Would it possible to allow one statement that merges When()
and Verify()
calls? Either like Verify(When())
or When().Verify()
? (Perhaps implemented by an automatically created hidden object's destructor, if that helped, so the verifications automatically happened when the current scope closed.) It would be especially nice to not have the same .Matching()
in two spots, on both When()
and Verify()
.
Would it be possible to have a strict mode, perhaps as a flag to Mock<>
or Mock<>.get()
that would assume any When()
expected .Exactly(1)
, and also at the end VerifyNoOtherInvocations()
? I realize others might not like this, but I'd love to be able to just use the When()
statements to create my exact sequence of invocations, without even having to add any extra syntax to the When()
calls.
Hi,
First let me start by saying that this is a great framework. I ran across it a few hours ago and already I was able to use it in a few unit tests, eliminating some self made mocking classes.
It also seems really robust and feature-rich.
I would like to propose / request a few features. I'll open a separate issue for each.
For this request, there might already be an implemented solution, but I couldn't find it. I also seem to not fully understand the conditions in which Verify() fails - since the order of calls to the various Verify*() macros matters.
We have a few unit tests each representing a flow. I want to be able to check the invocation of methods in my mocks after every step of the flow.
I use the Verify().Once() to make sure the correct method and parameters were called, and immediately VerifyNoOtherInvocations(mock) to make sure nothing else was called.
What I'd like to do then is to 'clear the table' for the next step, so I can once again call Once() (with different parameters, if needed) and VerifyNoOtherInvocations().
Doing just that seems to work, unless the same parameters repeat themselves, in which case Verify().Once() complains that the method was called more than once. I'd like to avoid the need for counting the calls by myself, especially since adding a step in the middle of the flow might require me to change everything.
What I suggest is a syntax such as:
Method(mock, methodName).ResetInvocations()
This will cause the internal structs to delete all the previously recorded invocations.
Do you have another solution? Or if not, is it possible to add it for the next version?
Thanks.
If I try to dynamic cast the underlying smart pointers to mocked objects it doenst work. The result is always null.
E.G.
class IBase
{
public:
virtual void methodA() = 0;
};
class Base : public IBase
{
public:
void methodA() override
{
cout << "Base::methodA";
}
};
class Derived : public Base
{
public:
void methodA() override
{
cout << "Derived::methodA";
}
};
Mock<Derived> mock;
When(Method(mock, methodA)).AlwaysReturn();
Derived& derived = mock.get();
struct DoNotDelete { void operator()(Derived* p) const { } };
shared_ptr<Derived> derivedSPtr = shared_ptr<Derived>(&derived, DoNotDelete());
//This version works #1
//shared_ptr<Derived> derivedSPtr(new Derived());
set<shared_ptr<Base>> set;
set.insert(derivedSPtr);
for (auto item : set)
{
shared_ptr<Base> b1 = item;
b1->methodA();
shared_ptr<Derived> d1 = dynamic_pointer_cast<Derived>(b1);
//Next line fails.
//d1 is always null for the mocked version. If a real Derived object is used like the line commented out above #1 it works fine.
d1->methodA();
}
Unit tests for FakeIt is failing on Visual Studio. By looking at the code I believe it came from:
Is FakeIt planning to support x64 on Windows? If so let's get this fixed I don't minding lending a hand=)
I'm trying to use fakeit for a project of mine and I can't get anything to compile properly. This seems like a pretty straight forward interface, but I must be missing something (VS2013 Professional).
My Unit Test:
TEST_METHOD(CreateEntity_ValidEntity) { fakeit::Mock<EntityAccess::IEntityWrangler> mock; fakeit::When(Method(mock, CreateBlankEntity)) .Return(CoreIOC::ClassRepository::BuildObjectByName<EntityAccess::IEntity>("EntityBase")); auto wrangler = mock.get();
My Interface:
'namespace EntityAccess {
class NATIVEINTERFACE IEntityWrangler {
public:
typedef std::shared_ptr Ptr_t;
virtual ~IEntityWrangler() {}
virtual void SetConfiguration(const DataAccess::IConfiguration::Ptr_t &config) = 0;
virtual IEntity::Ptr_t CreateBlankEntity(const char *entityType) = 0;
virtual void GetEntityData(const IEntity::Ptr_t &filterEntity, IEntity::List_t &resultEntities) = 0;
virtual void PersistEntityData(IEntity::Ptr_t &e) = 0;
virtual void PersistEntityData(const IEntity::Ptr_t &filter, IEntity::Ptr_t &data) = 0;
virtual void DestroyEntityData(IEntity::Ptr_t &e) = 0;
virtual void DestroyEntityData(const IEntity::Ptr_t &filter, IEntity::List_t &deletedEntities) = 0;
virtual const std::vectorstd::string &entityNames() const = 0;
};
}'
Sorry about the formatting, but I am struggling with the code blocks!
I may just be doing it wrong, but I can't find a way to return from a const overload. I checked the project's unit test code and didn't find any examples.
Support for the following situation would be highly appreciated.
virtual Foo& GetBar();
virtual const Foo& GetBar() const;
Love the framework, thanks for all of your effort!
Hello.
I've noticed a lot of memory being allocated when using AlwaysDo in my tests. Memory usage steadily increases when a mock is used in long-running loop. You should be able to reproduce it by running the code below.
#include <standalone/fakeit.hpp>
using namespace fakeit;
struct Foo { virtual void bar() = 0; };
int main() {
Mock<Foo> fooMock;
When(Method(fooMock, bar)).AlwaysDo([] { });
Foo &foo = fooMock.get();
while (true) { foo.bar(); }
return 0;
}
Is this a bug in the library, or am I doing something wrong? Thanks for your answer.
Sometimes it can be convenient to use the methods of the real underlying class that is being mocked rather that having to stub out everything. Is that possible with FakeIt?
Thanks,
JP
For historic reasons, lots of project have APIs that use output parameters extensively. So, it would be nice and save a lot of time modifying existing code in order to mock it if there is direct support for this kind APIs.
And another one:
I'm using Boost test, MSVC 2013.
When there's a verify error, the info is printed (test case name, file and line) but it appears on the same line as BoostTestFakeit.hpp(22), and is not exactly in the correct format (line number in parentheses, and I think absolute path is also required), so I can't double click in the output panel to take me to the correct location in the unit test source file.
It might sound nit-picky, but searching for the correct source file in a large project instead of double clicking is time wasting...
Thanks.
Hi!
Basically, as I understand it, when creating a mock I have to explicitly do Fake(Method(,)) for each method that might get called during testing. Currently I'm working on some legacy code that does alot in alot of places, basically forcing me to Fake each method explicitly to even get past the method being tested.
Could it be possible to, by default by choice, make all invocations be faked/ignored/return defaults ?
This is how most other mocking-frameworks behave coming from .Net, (even Isolator++ behave like this to my knowledge).
Would remove alot of boilerplate code!
The code is like this
struct Paint
{
Paint(shared_ptr p_pen) :m_pen(p_pen) {};
void RePain()
{
m_pen->Do();
}
shared_ptr m_pen;
}
struct IPen
{
virtual Do() =0;
}
When I testing Paint, I want to pass a mocked IPen into Paint.
But how can I pass the shared_ptr of IPen into Paint?
If I can change the design to make Paint to have reference on IPen might be better. But If there a solution that I can use mock a shared_ptr?
FakeIt currently only supports GCC and MSVC. What's required to support clang?
Hello!
I have an interface that has to be injected into an object which is going to take the ownership of the interface pointer. Here's an example
class Interface { virtual ~Interface() {}; }
class Owner
{
public:
Owner( Interface* interface )
{
this->interface = interface;
}
~Owner()
{
delete interface;
}
private:
Interface* interface;
}
Mock<Interface> interface;
Owner* owner = new Owner(&interface.get());
When(Dtor(mockedPresentation)).AlwaysReturn();
delete owner;
During the
delete interface;
in the Owner destructor i got a crash in fakeit:
void *getCookie(int index)
{
return _firstMethod[-2 - index];
}
The index value is 0 if that could help.
I'm not sure if I can treat the reference returned by Mock<>::get() as a heap allocated instance. Am I using the library in the wrong way?
When trying to set up an expectation for a method that takes a non copyable argument such as a unique_ptr, I get the following message from the compiler (mscv 2015)
attempting to reference a deleted function
Basically the class looks like this.
struct SomeInterface
{
virtual ~SomeInterface(){}
virtual void foo(std::unique_ptr<int> ) const = 0;
};
and the following code is enough to trigger the error.
Mock<SomeInterface> mock
Verify( Method(mock, foo) );
As passing unique_ptr by value is the preferred method for passing "sink" values, this is not that uncommon.
Building on MinGW 4.8.1 (and 4.8.2)
../include/fakeit/VerifyNoOtherInvocationsVerificationProgress.hpp:24:42: note:
in expansion of macro 'THROWS'
~VerifyNoOtherInvocationsExpectation() THROWS {
^
../include/mockutils/Macros.hpp:13:22: error: expected type-specifier before '..
.' token
#define THROWS throw(...)
^
../include/fakeit/VerifyNoOtherInvocationsVerificationProgress.hpp:89:50: note:
in expansion of macro 'THROWS'
~VerifyNoOtherInvocationsVerificationProgress() THROWS {};
^
../include/mockutils/Macros.hpp:13:22: error: expected type-specifier before '..
.' token
#define THROWS throw(...)
^
../include/fakeit/WhenFunctor.hpp:25:31: note: in expansion of macro 'THROWS'
virtual ~StubbingProgress() THROWS {
^
Which version of gcc should I be using?
RecordedMethodBody.cpp:124 and below
actualInvoaction -> actualInvocation
In my project I've replaced your formatter with the following, which allows any type with the standard operator<<
defined to be formatted, including my custom types. Just sharing in case you like it. Feel free to use or discard as you please.
template <typename T>
struct Formatter
{
static auto format(T const &val) -> decltype((std::cout << val), std::string())
{
std::ostringstream os;
os << val;
return os.str();
}
static std::string format(...)
{
return "?";
}
};
hey.
iam pretty new to FakeIt but I stumbled across something that is confusing me. I can't mock simple inherited classes.
Take that code for example
class HandlerBase
{};
class TMessage {};
class Handler : public HandlerBase
{
public:
void Handle(TMessage message)
{
HandleMessage(message);
}
virtual void HandleMessage(TMessage m) {};
};
SCENARIO()
{
fakeit::Mock<Handler> m;
}
I get that compiler error: "Can't mock a type with multiple inheritance"
Iam using vs2015, fakeit and CATCH to run that code…And forgot to much about c++ to look closer…
Any ideas on that issue?
How am I supposed to pass a mock as unique pointer?
For example:
class Object
{
public:
~Object() {}
virtual void DoSomething() = 0;
};
class Handler
{
public:
explicit Handler(std::unique_ptr<Object> SomeObject)
: m_Object(std::move(SomeObject))
{
}
void Handle()
{
m_Object->DoSomething();
}
private:
std::unique_ptr<Object> m_Object;
};
TEST()
{
Mock<Object> ObjectMock;
When(Method(ObjectMock, DoSomething)).AlwaysReturn();
Object* SomeObject = &ObjectMock.get();
Handler SomeHandler(make_unique(SomeObject));
SomeHandler.Handle();
Verify(Method(ObjectMock, DoSomething)).Once();
}
This code crashes on exiting the test because both Mock
and Handler
take ownership of the Object
instance. Could you add some release method to Mock
which releases ownership but still holds a weak reference to the object? Or is there another way to handle this?
I've been taking a look at this framework and I find it very promising - I haven't seen much else quite like it yet.
However, one feature I feel would be very useful is the ability to specify only some of the arguments to a function, without having to put in a lambda.
For example, gmock uses a '' to specify any, plus Ge for >=, LT for <=, etc.
So a function f(a,b) could be used with Using(, 2) which would let 'a' be any value but specify that b must be 2. Or Using(Ge(1),2) would specify that 'a' is greater than 1 and 'b' is 2.
The new streaming stuff causes the Visual Studio causes compiler crashes in Visual Studio 2013 when functions have enum class arguments (eg: see the test case I added in this commit).
I've tried moving around the decltype() specification (eg: putting it before the function - with suitable std::declval uses - in place of the auto, or putting it as an argument), but it seems to be the fact that decltype(s << t) is being used where t is an enum class instance that is causing the issue.
Doing something like
decltype(operator<<(std::decltype<std::ostream&>(), std::decltype<T1>()))
seems to fix the issue, but breaks the unit tests.
I am using FakeIt to unit test a Qt based application. Method stubbing based on a QString
parameter works like a charm -- i.e. the correct stubbed values are returned. When trying to do method call verification based on a QString
parameter I am running into problems though.
Here is a (rather) minimal example:
// interface
class Foo {
public:
virtual bool bar(const QString &value) {
return false;
}
};
// test code
Mock<Foo> mock;
When(Method(mock, bar)).AlwaysReturn(false);
When(Method(mock, bar).Using(QString("foo"))).AlwaysReturn(true);
CHECK(foo.bar(QString("foo"))); // returns true
CHECK(foo.bar("foo")); // returns true
CHECK(foo.bar("bar")); // returns false
Verify(Method(mock, bar)).Exactly(3_Times); // works
Verify(Method(mock, bar).Using("foo").Exactly(2_Times); // fails (0 matches)
Verify(Method(mock, bar).Using(QString("foo")).Exactly(2_Times); // fails (0 matches)
// maybe lower-level? (i.e Matching()) - crashes with SEGFAULT or SIGABRT
Verify(Method(mock, bar).Matching([](QString val){return val == "foo";}).Exactly(2_Times):
// sometimes prints:
// ASSERT: "size == 0 || offset < 0 || size_t(offset) >= sizeof(QArrayData)" in file /usr/local/opt/qt5/lib/QtCore.framework/Headers/qarraydata.h, line 54
Seems that FakeIt damages the internal structure of the QString
object, causing miscounting or crashes in the Verify
stage. I tried all kinds of variations of casting or explicit object construction for the method invocations with out any luck.
Any thoughts or ideas? Am I doing something stupid?
-- Many thanks.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.