• 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(const std::string& key) override;
OnInitializationCompleted(bool succeeded)28   void OnInitializationCompleted(bool succeeded) override {}
29 
30  private:
31   raw_ptr<DefaultPrefStore> pref_store_;
32 
33   int change_count_;
34 };
35 
MockPrefStoreObserver(DefaultPrefStore * pref_store)36 MockPrefStoreObserver::MockPrefStoreObserver(DefaultPrefStore* pref_store)
37     : pref_store_(pref_store), change_count_(0) {
38   pref_store_->AddObserver(this);
39 }
40 
~MockPrefStoreObserver()41 MockPrefStoreObserver::~MockPrefStoreObserver() {
42   pref_store_->RemoveObserver(this);
43 }
44 
OnPrefValueChanged(const std::string & key)45 void MockPrefStoreObserver::OnPrefValueChanged(const std::string& key) {
46   change_count_++;
47 }
48 
49 }  // namespace
50 
TEST(DefaultPrefStoreTest,NotifyPrefValueChanged)51 TEST(DefaultPrefStoreTest, NotifyPrefValueChanged) {
52   scoped_refptr<DefaultPrefStore> pref_store(new DefaultPrefStore);
53   MockPrefStoreObserver observer(pref_store.get());
54   std::string kPrefKey("pref_key");
55 
56   // Setting a default value shouldn't send a change notification.
57   pref_store->SetDefaultValue(kPrefKey, Value("foo"));
58   EXPECT_EQ(0, observer.change_count());
59 
60   // Replacing the default value should send a change notification...
61   pref_store->ReplaceDefaultValue(kPrefKey, Value("bar"));
62   EXPECT_EQ(1, observer.change_count());
63 
64   // But only if the value actually changed.
65   pref_store->ReplaceDefaultValue(kPrefKey, Value("bar"));
66   EXPECT_EQ(1, observer.change_count());
67 }
68