google / google/googletest

Allow for switching between NiceMock and StrictMock at runtime

Open
#3,660 4 comments 0 reactions 1 assignee Claimed by @CJ-Johnson View on GitHub
enhancement
Dominant language
C++
Stars
39.5k
Forks
10.9k
Avg merge
6d 13h
Merged PRs (30d)
1

Description

**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 `StrictMock`s, 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`:
```cpp
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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.