timer_unittest.cc 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2015 The Chromium 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. #include <string>
  5. #include <utility>
  6. #include "base/bind.h"
  7. #include "base/run_loop.h"
  8. #include "base/test/task_environment.h"
  9. #include "base/time/time.h"
  10. #include "components/component_updater/timer.h"
  11. #include "testing/gtest/include/gtest/gtest.h"
  12. using std::string;
  13. namespace component_updater {
  14. class ComponentUpdaterTimerTest : public testing::Test {
  15. public:
  16. ComponentUpdaterTimerTest()
  17. : task_environment_(
  18. base::test::SingleThreadTaskEnvironment::MainThreadType::UI) {}
  19. ~ComponentUpdaterTimerTest() override = default;
  20. private:
  21. base::test::SingleThreadTaskEnvironment task_environment_;
  22. };
  23. TEST_F(ComponentUpdaterTimerTest, Start) {
  24. class TimerClientMock {
  25. public:
  26. TimerClientMock(int max_count, base::OnceClosure quit_closure)
  27. : max_count_(max_count),
  28. quit_closure_(std::move(quit_closure)),
  29. count_(0) {}
  30. void OnTimerEvent() {
  31. ++count_;
  32. if (count_ >= max_count_)
  33. std::move(quit_closure_).Run();
  34. }
  35. int count() const { return count_; }
  36. private:
  37. const int max_count_;
  38. base::OnceClosure quit_closure_;
  39. int count_;
  40. };
  41. base::RunLoop run_loop;
  42. TimerClientMock timer_client_fake(3, run_loop.QuitClosure());
  43. EXPECT_EQ(0, timer_client_fake.count());
  44. Timer timer;
  45. const base::TimeDelta delay(base::Milliseconds(1));
  46. timer.Start(delay, delay,
  47. base::BindRepeating(&TimerClientMock::OnTimerEvent,
  48. base::Unretained(&timer_client_fake)));
  49. run_loop.Run();
  50. timer.Stop();
  51. EXPECT_EQ(3, timer_client_fake.count());
  52. }
  53. } // namespace component_updater