googletest icon indicating copy to clipboard operation
googletest copied to clipboard

Allow for switching between NiceMock and StrictMock at runtime

Open cbandera opened this issue 3 years ago • 4 comments

Why do we need this feature?

In my unittests I follow the AAA pattern (Arrange, Act, Assert), also I like to use test fixtures for moving common arrange steps into the SetUp() method. When using StrictMocks, every call to the mock object must be registered as expected. This get's difficult or at least cumbersome if I need to perform mutliple steps during the arrange statement.

Example: Consider following example: Given a statemachine that acts on a mock object. I want to write dedicated tests for each state and strictly test, that the protocol within this state is adhered to (here I want StrictMock behaviour). But as my API of the statemachine is designed to prevent misusage, I need to switch through a couple of states first for reaching my to-be-tested state (here I want NiceMock behaviour).

Describe the proposal

Given the current implementation, the decision of whether a Mock is Nice or Strict is already a runtime decision. Only the user interface to it is designed to be a compiletime decision. I propose to extend the interface by providing the following functions in gmock-spec-builders.h:

class Mock {
 public:
  ...
  // Converts the mock into a naggy mock (default)
  static void MakeNaggy(void* mock_obj);
  // Converts the mock into a nice mock
  static void MakeNice(void* mock_obj);
  // Converts the mock into a strict mock
  static void MakeStrict(void* mock_obj);
...

In the definition, these functions would then modify the static lookup map, the way the constructors of the Nice/StrictMock wrappers do.

Remarks I did try out several things, like making use of VerifyAndClearExpectations but it is explicitly stated in the documentation that it's undefined behaviour to set new expectations after this call. My current solution is the "Check Point" solution from the CookBook, but it's rather cumbersome to set up all "wildcard" expectations for every method of every mock.

Maybe there is a design decision that I am not aware of, which discourages the proposed feature or maybe there is a existing way of achieving the same. If so, I'd be happy to hear about it. If not, I'd be happy to draft a PR with the requested feature.

cbandera avatar Nov 12 '21 22:11 cbandera