• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 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 #include "components/prefs/default_pref_store.h"
6 #include "base/memory/raw_ptr.h"
7 #include "testing/gtest/include/gtest/gtest.h"
8 
9 using base::Value;
10 
11 namespace {
12 
13 class MockPrefStoreObserver : public PrefStore::Observer {
14  public:
15   explicit MockPrefStoreObserver(DefaultPrefStore* pref_store);
16 
17   MockPrefStoreObserver(const MockPrefStoreObserver&) = delete;
18   MockPrefStoreObserver& operator=(const MockPrefStoreObserver&) = delete;
19 
20   ~MockPrefStoreObserver() override;
21 
change_count()22   int change_count() {
23     return change_count_;
24   }
25 
26   // PrefStore::Observer implementation:
27   void OnPrefValueChanged(std::string_view key) override;
28 
29  private:
30   raw_ptr<DefaultPrefStore> pref_store_;
31 
32   int change_count_;
33 };
34 
MockPrefStoreObserver(DefaultPrefStore * pref_store)35 MockPrefStoreObserver::MockPrefStoreObserver(DefaultPrefStore* pref_store)
36     : pref_store_(pref_store), change_count_(0) {
37   pref_store_->AddObserver(this);
38 }
39 
~MockPrefStoreObserver()40 MockPrefStoreObserver::~MockPrefStoreObserver() {
41   pref_store_->RemoveObserver(this);
42 }
43 
OnPrefValueChanged(std::string_view key)44 void MockPrefStoreObserver::OnPrefValueChanged(std::string_view key) {
45   change_count_++;
46 }
47 
48 }  // namespace
49 
TEST(DefaultPrefStoreTest,NotifyPrefValueChanged)50 TEST(DefaultPrefStoreTest, NotifyPrefValueChanged) {
51   scoped_refptr<DefaultPrefStore> pref_store(new DefaultPrefStore);
52   MockPrefStoreObserver observer(pref_store.get());
53   std::string kPrefKey("pref_key");
54 
55   // Setting a default value shouldn't send a change notification.
56   pref_store->SetDefaultValue(kPrefKey, Value("foo"));
57   EXPECT_EQ(0, observer.change_count());
58 
59   // Replacing the default value should send a change notification...
60   pref_store->ReplaceDefaultValue(kPrefKey, Value("bar"));
61   EXPECT_EQ(1, observer.change_count());
62 
63   // But only if the value actually changed.
64   pref_store->ReplaceDefaultValue(kPrefKey, Value("bar"));
65   EXPECT_EQ(1, observer.change_count());
66 }
67