In unit testing, fakes and stubs are used to create test isolation: fakes: simulate the unit under test, control behavior and verify interactions, used to replace external or difficult-to-test dependencies. Stub: A special fake, simulated function or method that always returns a fixed value or performs a specified action, used to replace time-consuming or unstable dependencies.
C Usage scenarios of forgery and stubs in unit testing
In unit testing, forgery and stubs are used to create test isolation Two powerful technologies for the environment. They allow test developers to test specific code without relying on other components.
Mock
Fake is the creation of a simulated version of the unit under test that can control its behavior and verify its interactions. Fake is often used to replace external or hard-to-test dependencies.
For example:
class UserService { public: virtual User GetUser(int id) = 0; }; class UserServiceMock : public UserService { public: MOCK_METHOD(User, GetUser, (int id), (override)); };
In this example, UserServiceMock
is a fake of UserService
, used to control GetUser()
method's behavior so that it can be verified in tests.
Stub (Stub)
A stub is a special kind of forgery that simulates a function or method that always returns a fixed value or performs a specified action. Stubs are often used to replace time-consuming or unstable dependencies.
For example:
// SleepStub 不实际调用 sleep 函数,而是返回一个固定的值 class SleepStub { public: static void Sleep(int) {} };
Use cases
Fake and stub have multiple use cases in unit tests, including:
Practical case
Suppose we have a function that gets the user from UserService
and updates the user's password in the database:
void UpdateUserPassword(int userId, const std::string& newPassword) { auto user = userService.GetUser(userId); user.SetPassword(newPassword); db.UpdateUser(user); }
We can create a unit test case using UserServiceMock
to fake UserService
and verify the correct behavior of the function:
TEST(UpdateUserPassword, UpdatesPassword) { UserServiceMock userServiceMock; User expectedUser; EXPECT_CALL(userServiceMock, GetUser(userId)).WillOnce(Return(expectedUser)); UpdateUserPassword(userId, newPassword); // Assert that the user password was set correctly ASSERT_EQ(expectedUser.GetPassword(), newPassword); }
In this test case, We ensure that GetUser()
is called once and returns the expected user. We then assert that the user's password has been updated correctly.
The above is the detailed content of What are the usage scenarios of faking and stubbing in C++ unit testing?. For more information, please follow other related articles on the PHP Chinese website!