• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_TEST_GMOCK_MOVE_SUPPORT_H_
6 #define BASE_TEST_GMOCK_MOVE_SUPPORT_H_
7 
8 #include <cstddef>
9 #include <tuple>
10 #include <utility>
11 
12 // A similar action as testing::SaveArg, but it does an assignment with
13 // std::move() instead of always performing a copy.
14 template <size_t I = 0, typename T>
MoveArg(T * out)15 auto MoveArg(T* out) {
16   return [out](auto&&... args) {
17     *out = std::move(std::get<I>(std::tie(args...)));
18   };
19 }
20 
21 // Moves the `I`th argument to `*out` and returns `return_value`.
22 // This addresses that `DoAll(MoveArg(), Return())` does not work for moveable
23 // types passed by value, since the first action only receives a read-only view
24 // of its arguments.
25 //
26 // Example:
27 //
28 // using MoveOnly = std::unique<int>;
29 // struct MockFoo {
30 //   MOCK_METHOD(bool, Fun, (MoveOnly), ());
31 // };
32 //
33 // MoveOnly result;
34 // MockFoo foo;
35 // EXPECT_CALL(foo, Fun).WillOnce(MoveArgAndReturn(&result, true));
36 // EXPECT_TRUE(foo.Fun(std::make_unique<int>(123)));
37 // EXPECT_THAT(result, testing::Pointee(123));
38 template <size_t I = 0, typename T1, typename T2>
MoveArgAndReturn(T1 * out,T2 && return_value)39 auto MoveArgAndReturn(T1* out, T2&& return_value) {
40   return [out, value = std::forward<T2>(return_value)](auto&&... args) mutable {
41     *out = std::move(std::get<I>(std::tie(args...)));
42     return std::forward<T2>(value);
43   };
44 }
45 
46 #endif  // BASE_TEST_GMOCK_MOVE_SUPPORT_H_
47