eranpeer / FakeIt

C++ mocking made easy. A simple yet very expressive, headers only library for c++ mocking.
MIT License
1.24k stars 170 forks source link

User-defined matchers taking an argument #111

Closed djleach-belcan closed 6 years ago

djleach-belcan commented 6 years ago

Is it possible to define custom matchers taking an argument?

For example say I have:

struct Point
{
    double x;
    double y;
};

class IPointUser
{
public:
    virtual void UsePoint(Point const& point) = 0;
};

I'd like to be able to verify that UsePoint is called with a test-specified x-coordinate, without regard to the y-coordinate:

Mock<IPointUser> mockPointUser{};

Point point1{1,2};
Point point2{2,3};
mockPointUser.get().UsePoint(point1);
mockPointUser.get().UsePoint(point2);
// [...custom matcher called IsAtX...]
Verify(Method(mockPointUser, UsePoint).Using(IsAtX(1)));
Verify(Method(mockPointUser, UsePoint).Using(IsAtX(2)));
djleach-belcan commented 6 years ago

Sorry to keep flooding your repo with issues and my own replies but I found a bit of a work around:

auto IsAtX = [](double x)
{
    return [x](auto&& point) { return point.x == x; }; // Pretend this is a good way to compare floating-point numbers
};

Perhaps that's elegant enough to not require extending FakeIt to support such things.

eranpeer commented 6 years ago

Yep, That's the right way to do it with FakeIt.