1 // Copyright 2015 The Chromium OS Authors. All rights reserved. 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 LIBBRILLO_BRILLO_MESSAGE_LOOPS_MOCK_MESSAGE_LOOP_H_ 6 #define LIBBRILLO_BRILLO_MESSAGE_LOOPS_MOCK_MESSAGE_LOOP_H_ 7 8 #include <gmock/gmock.h> 9 10 #include <base/location.h> 11 #include <base/test/simple_test_clock.h> 12 #include <base/time/time.h> 13 14 #include <brillo/brillo_export.h> 15 #include <brillo/message_loops/fake_message_loop.h> 16 #include <brillo/message_loops/message_loop.h> 17 18 namespace brillo { 19 20 // The MockMessageLoop is a mockable MessageLoop that will by default act as a 21 // FakeMessageLoop. It is possible to set expectations with EXPECT_CALL without 22 // any action associated and they will call the same methods in the underlying 23 // FakeMessageLoop implementation. 24 // This message loop implementation is useful to check interaction with the 25 // message loop when running unittests. 26 class BRILLO_EXPORT MockMessageLoop : public MessageLoop { 27 public: 28 // Create a FakeMessageLoop optionally using a SimpleTestClock to update the 29 // time when Run() or RunOnce(true) are called and should block. MockMessageLoop(base::SimpleTestClock * clock)30 explicit MockMessageLoop(base::SimpleTestClock* clock) 31 : fake_loop_(clock) { 32 // Redirect all actions to calling the underlying FakeMessageLoop by 33 // default. For the overloaded methods, we need to disambiguate between the 34 // different options by specifying the type of the method pointer. 35 ON_CALL(*this, PostDelayedTask(::testing::_, ::testing::_, ::testing::_)) 36 .WillByDefault(::testing::Invoke( 37 &fake_loop_, 38 static_cast<TaskId(FakeMessageLoop::*)( 39 const base::Location&, 40 base::OnceClosure, 41 base::TimeDelta)>( 42 &FakeMessageLoop::PostDelayedTask))); 43 ON_CALL(*this, CancelTask(::testing::_)) 44 .WillByDefault(::testing::Invoke(&fake_loop_, 45 &FakeMessageLoop::CancelTask)); 46 ON_CALL(*this, RunOnce(::testing::_)) 47 .WillByDefault(::testing::Invoke(&fake_loop_, 48 &FakeMessageLoop::RunOnce)); 49 } 50 ~MockMessageLoop() override = default; 51 52 MOCK_METHOD(TaskId, 53 PostDelayedTask, 54 (const base::Location&, base::OnceClosure, base::TimeDelta), 55 (override)); 56 using MessageLoop::PostDelayedTask; 57 MOCK_METHOD(bool, CancelTask, (TaskId), (override)); 58 MOCK_METHOD(bool, RunOnce, (bool), (override)); 59 60 // Returns the actual FakeMessageLoop instance so default actions can be 61 // override with other actions or call fake_loop()62 FakeMessageLoop* fake_loop() { 63 return &fake_loop_; 64 } 65 66 private: 67 FakeMessageLoop fake_loop_; 68 69 DISALLOW_COPY_AND_ASSIGN(MockMessageLoop); 70 }; 71 72 } // namespace brillo 73 74 #endif // LIBBRILLO_BRILLO_MESSAGE_LOOPS_MOCK_MESSAGE_LOOP_H_ 75