Blog Home

Only Expect State-Changing Method Calls

2017-12-11

Expecting calls to methods that don't change state can make a test brittle, less readable, and provide a false sense of security.

Bad

TEST(UserAuthorizer, AddPermissionToDatabase) {
  UserAuthorizer user_authorizer(mock_user_service_, mock_permission_db_);

  EXPECT_CALL(mock_user_service_, IsUserActive(kUser));
  EXPECT_CALL(mock_permission_db_, GetPermission(kUser));
  EXPECT_CALL(mock_permission_db_, IsValidPermission(kReadAccess));
  EXPECT_CALL(mock_permission_db_, AddPermission(kUser, kReadAccess));

  user_authorizer.GrantPermission(kUser, kReadAccess);
}

It is fine, however, to use non-state-changing methods for simulating test conditions.

Good

ON_CALL(mock_user_service_, IsUserActive(kUser)).WillByDefault(Return(false));

With unnecessary EXPECT_CALLs removed, the test becomes:

Good

Test(UserAuthorizer, AddPermissionToDatabase) {
  UserAuthorizer user_authorizer(mock_user_service_, mock_permission_db_);

  EXPECT_CALL(mock_permission_db_, AddPermission(kUser, kReadAccess));

  user_authorizer.GrantPermission(kUser, kReadAccess);
}