Spy some dependencies #4510
Replies: 2 comments 1 reply
-
Please see https://google.github.io/googletest/gmock_cook_book.html#mocking-free-functions. |
Beta Was this translation helpful? Give feedback.
-
Here is the pseudo-code which is similar to our production code in practice: char *do1Thing()
{
char *info = new char[64];
// populate info with some important information
return info;
}
void do2Things()
{
// do some dangerous operations here
}
void do3Thing(char *info)
{
// use info here
delete info;
}
void ProductionCode()
{
char *info = do1Thing();
do2Thing();
do3Thing(info);
} In the code above, we create a dynamic memory in Now we need to write a unit test. The case is to "make sure all of the resources are released when any exception is thrown". So we need invoke #include "ProductionCode.h"
TEST()
{
mock("do2Thing", [](){ throw "exception"; });
ProductionCode();
mock.assertThrow("exception");
} Here we write a fake In other languages, such as node.js, we can do it like this. Every function including the system function could be mocked. Does this way work in C++? If no, what is the best practice? See the mock of node.js native test: import { mock } from "node:test";
const tt = {
f0() {
console.log("f0");
this.f1();
},
f1() {
console.log("f1");
},
};
mock.method(tt, "f1", () => console.log("mock"));
tt.f0(); The output is: f0
mock It means that |
Beta Was this translation helpful? Give feedback.
-
Suppose we have a function in my production code.
Now we need write a unit test for this function. And we want to spy
do2Thing()
and let it throw an exception. Pseudo-code is like this:Is it possible to do this?
Beta Was this translation helpful? Give feedback.
All reactions