Possseidon / dang-lib

A C++ library, providing a variety of useful classes focused around game developement.
3 stars 1 forks source link

Implement function stubs that keep track of invocations. #57

Closed Possseidon closed 3 years ago

Possseidon commented 3 years ago

This is very useful for writing unit-tests, which is why I also decided to integrate them very thoroughly with Catch2's matching system:

// create a new stub that simply returns true
auto my_stub = dutils::Stub<bool(int, int, int)>(true);

// optionally give a name to the stub and its parameters
my_stub.setInfo({"my_stub", {"a", "b", "c"}});

// the stub has not been called yet
CHECK_THAT(my_stub, !Called(my_stub));

// can be called like any old function (that's the whole point!)
my_stub(1, 2, 3);

// the stub was now called exactly once with "1, 2, 3"
CHECK_THAT(my_stub, CalledWith(my_stub, 1, 2, 3));

// call it again... the above check would now fail
my_stub(4, 5, 6);

// the stub must have been called exactly twice
CHECK_THAT(my_stub, Called(my_stub, 2));

 // the stub's two invocations must be "1, 2, 3" and "4, 5, 6"
CHECK_THAT(my_stub, CalledWith(my_stub, invocation(0), 1, 2, 3));
CHECK_THAT(my_stub, CalledWith(my_stub, invocation(1), 4, 5, 6));

If a match fails, Catch2 will list all invocations of the stub and even tell you exactly which parameters of which invocations didn't match up.

TODO