base: Remove MessageLoop usage from tests

This patch removes MessageLoop usage from base unittests *except* for the
following ones:

 - MessageLoop's own unit and perf tests
 - SequenceManager unit and perf tests (need to keep MessageLoop interop
   working for now)
 - FileWatcher (needs a controlled threading environment)
 - ObserverListThreadSafe (ditto)
 - TaskObserverPerfTest (measures MessageLoop overhead)
 - ThreadTest (Thread API needs updating)

These tests will eventually be migrated to the MessageLoop's
replacement or removed.

Bug: 891670
Change-Id: Ic32495a77819b9644cca823d64dea77754cf5c84
Reviewed-on: https://chromium-review.googlesource.com/c/1336147
Reviewed-by: Sami Kyöstilä <[email protected]>
Reviewed-by: François Doray <[email protected]>
Commit-Queue: Sami Kyöstilä <[email protected]>
Cr-Commit-Position: refs/heads/master@{#609257}
diff --git a/base/android/application_status_listener_unittest.cc b/base/android/application_status_listener_unittest.cc
index 37e8e1c..f904dd0 100644
--- a/base/android/application_status_listener_unittest.cc
+++ b/base/android/application_status_listener_unittest.cc
@@ -9,9 +9,9 @@
 #include "base/bind.h"
 #include "base/callback_forward.h"
 #include "base/logging.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/synchronization/waitable_event.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/threading/thread.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -45,8 +45,7 @@
       : state_(kInvalidApplicationState),
         event_(WaitableEvent::ResetPolicy::AUTOMATIC,
                WaitableEvent::InitialState::NOT_SIGNALED),
-        thread_("ApplicationStatusTest thread"),
-        main_() {}
+        thread_("ApplicationStatusTest thread") {}
 
   void Run() {
     // Start the thread and tell it to register for events.
@@ -93,14 +92,14 @@
   ApplicationState state_;
   base::WaitableEvent event_;
   base::Thread thread_;
-  base::MessageLoop main_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
   std::unique_ptr<ApplicationStatusListener> listener_;
 };
 
 }  // namespace
 
 TEST(ApplicationStatusListenerTest, SingleThread) {
-  MessageLoop message_loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
 
   ApplicationState result = kInvalidApplicationState;
 
diff --git a/base/cancelable_callback_unittest.cc b/base/cancelable_callback_unittest.cc
index 42e753f..0c254a8 100644
--- a/base/cancelable_callback_unittest.cc
+++ b/base/cancelable_callback_unittest.cc
@@ -10,9 +10,9 @@
 #include "base/bind_helpers.h"
 #include "base/location.h"
 #include "base/memory/ref_counted.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/single_thread_task_runner.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/threading/thread_task_runner_handle.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -166,10 +166,10 @@
   EXPECT_TRUE(cancelable.IsCancelled());
 }
 
-// CancelableCallback posted to a MessageLoop with PostTask.
-//  - Callbacks posted to a MessageLoop can be cancelled.
+// CancelableCallback posted to a task environment with PostTask.
+//  - Posted callbacks can be cancelled.
 TEST(CancelableCallbackTest, PostTask) {
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
 
   int count = 0;
   CancelableClosure cancelable(base::Bind(&Increment,
@@ -182,7 +182,7 @@
 
   ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, cancelable.callback());
 
-  // Cancel before running the message loop.
+  // Cancel before running the tasks.
   cancelable.Cancel();
   RunLoop().RunUntilIdle();
 
diff --git a/base/debug/task_annotator_unittest.cc b/base/debug/task_annotator_unittest.cc
index 70e327c2..c85edfdc 100644
--- a/base/debug/task_annotator_unittest.cc
+++ b/base/debug/task_annotator_unittest.cc
@@ -11,7 +11,6 @@
 #include "base/bind_helpers.h"
 #include "base/callback.h"
 #include "base/macros.h"
-#include "base/message_loop/message_loop.h"
 #include "base/pending_task.h"
 #include "base/run_loop.h"
 #include "base/strings/stringprintf.h"
@@ -134,7 +133,7 @@
 
 // Ensure the task backtrace populates correctly.
 TEST_F(TaskAnnotatorBacktraceIntegrationTest, SingleThreadedSimple) {
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
   const Location location0 = FROM_HERE;
   const Location location1 = FROM_HERE;
   const Location location2 = FROM_HERE;
@@ -148,7 +147,7 @@
   // last 4 parents are kept).
   OnceClosure task5 = BindOnce(
       &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-      Unretained(this), loop.task_runner(), location5, FROM_HERE,
+      Unretained(this), ThreadTaskRunnerHandle::Get(), location5, FROM_HERE,
       ExpectedTrace({location4.program_counter(), location3.program_counter(),
                      location2.program_counter(), location1.program_counter()}),
       run_loop.QuitClosure());
@@ -156,31 +155,31 @@
   // Task i=4/3/2/1/0 have tasks [0,i) as parents.
   OnceClosure task4 = BindOnce(
       &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-      Unretained(this), loop.task_runner(), location4, location5,
+      Unretained(this), ThreadTaskRunnerHandle::Get(), location4, location5,
       ExpectedTrace({location3.program_counter(), location2.program_counter(),
                      location1.program_counter(), location0.program_counter()}),
       std::move(task5));
   OnceClosure task3 = BindOnce(
       &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-      Unretained(this), loop.task_runner(), location3, location4,
+      Unretained(this), ThreadTaskRunnerHandle::Get(), location3, location4,
       ExpectedTrace({location2.program_counter(), location1.program_counter(),
                      location0.program_counter()}),
       std::move(task4));
   OnceClosure task2 = BindOnce(
       &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-      Unretained(this), loop.task_runner(), location2, location3,
+      Unretained(this), ThreadTaskRunnerHandle::Get(), location2, location3,
       ExpectedTrace({location1.program_counter(), location0.program_counter()}),
       std::move(task3));
-  OnceClosure task1 =
-      BindOnce(&TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-               Unretained(this), loop.task_runner(), location1, location2,
-               ExpectedTrace({location0.program_counter()}), std::move(task2));
+  OnceClosure task1 = BindOnce(
+      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
+      Unretained(this), ThreadTaskRunnerHandle::Get(), location1, location2,
+      ExpectedTrace({location0.program_counter()}), std::move(task2));
   OnceClosure task0 =
       BindOnce(&TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-               Unretained(this), loop.task_runner(), location0, location1,
-               ExpectedTrace({}), std::move(task1));
+               Unretained(this), ThreadTaskRunnerHandle::Get(), location0,
+               location1, ExpectedTrace({}), std::move(task1));
 
-  loop.task_runner()->PostTask(location0, std::move(task0));
+  ThreadTaskRunnerHandle::Get()->PostTask(location0, std::move(task0));
 
   run_loop.Run();
 }
@@ -189,7 +188,7 @@
 TEST_F(TaskAnnotatorBacktraceIntegrationTest, MultipleThreads) {
   test::ScopedTaskEnvironment scoped_task_environment;
 
-  // Use diverse task runners (a MessageLoop on the main thread, a TaskScheduler
+  // Use diverse task runners (a task environment main thread, a TaskScheduler
   // based SequencedTaskRunner, and a TaskScheduler based
   // SingleThreadTaskRunner) to verify that TaskAnnotator can capture backtraces
   // for PostTasks back-and-forth between these.
@@ -278,7 +277,7 @@
 
 // Ensure nesting doesn't break the chain.
 TEST_F(TaskAnnotatorBacktraceIntegrationTest, SingleThreadedNested) {
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
   const Location location0 = FROM_HERE;
   const Location location1 = FROM_HERE;
   const Location location2 = FROM_HERE;
@@ -315,19 +314,19 @@
   // 4.
   OnceClosure task5 = BindOnce(
       &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-      Unretained(this), loop.task_runner(), location5, FROM_HERE,
+      Unretained(this), ThreadTaskRunnerHandle::Get(), location5, FROM_HERE,
       ExpectedTrace({location4.program_counter(), location3.program_counter(),
                      location2.program_counter(), location1.program_counter()}),
       run_loop.QuitClosure());
   OnceClosure task4 = BindOnce(
       &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-      Unretained(this), loop.task_runner(), location4, location5,
+      Unretained(this), ThreadTaskRunnerHandle::Get(), location4, location5,
       ExpectedTrace({location3.program_counter(), location2.program_counter(),
                      location1.program_counter(), location0.program_counter()}),
       std::move(task5));
   OnceClosure task3 = BindOnce(
       &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-      Unretained(this), loop.task_runner(), location3, location4,
+      Unretained(this), ThreadTaskRunnerHandle::Get(), location3, location4,
       ExpectedTrace({location2.program_counter(), location1.program_counter(),
                      location0.program_counter()}),
       std::move(task4));
@@ -338,7 +337,7 @@
 
   OnceClosure task2 = BindOnce(
       &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-      Unretained(this), loop.task_runner(), location2, location3,
+      Unretained(this), ThreadTaskRunnerHandle::Get(), location2, location3,
       ExpectedTrace({location1.program_counter(), location0.program_counter()}),
       std::move(run_task_3_then_quit_nested_loop1));
 
@@ -357,11 +356,11 @@
 
   OnceClosure task0 =
       BindOnce(&TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
-               Unretained(this), loop.task_runner(), location0, location1,
-               ExpectedTrace({}), std::move(task1));
+               Unretained(this), ThreadTaskRunnerHandle::Get(), location0,
+               location1, ExpectedTrace({}), std::move(task1));
 
-  loop.task_runner()->PostTask(location0, std::move(task0));
-  loop.task_runner()->PostTask(
+  ThreadTaskRunnerHandle::Get()->PostTask(location0, std::move(task0));
+  ThreadTaskRunnerHandle::Get()->PostTask(
       FROM_HERE, BindOnce(&RunLoop::Run, Unretained(&nested_run_loop1)));
 
   run_loop.Run();
diff --git a/base/deferred_sequenced_task_runner_unittest.cc b/base/deferred_sequenced_task_runner_unittest.cc
index 5cb220f..ce92392 100644
--- a/base/deferred_sequenced_task_runner_unittest.cc
+++ b/base/deferred_sequenced_task_runner_unittest.cc
@@ -9,10 +9,11 @@
 #include "base/callback_forward.h"
 #include "base/location.h"
 #include "base/memory/ref_counted.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/single_thread_task_runner.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/threading/thread.h"
+#include "base/threading/thread_task_runner_handle.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -56,10 +57,10 @@
 
  protected:
   DeferredSequencedTaskRunnerTest()
-      : loop_(),
-        runner_(new DeferredSequencedTaskRunner(loop_.task_runner())) {}
+      : runner_(
+            new DeferredSequencedTaskRunner(ThreadTaskRunnerHandle::Get())) {}
 
-  MessageLoop loop_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
   scoped_refptr<DeferredSequencedTaskRunner> runner_;
   mutable Lock lock_;
   std::vector<int> executed_task_ids_;
@@ -205,7 +206,7 @@
                          std::move(quit_closure).Run();
                        },
                        &run_called, run_loop.QuitClosure()));
-  runner->StartWithTaskRunner(loop_.task_runner());
+  runner->StartWithTaskRunner(ThreadTaskRunnerHandle::Get());
   run_loop.Run();
   EXPECT_TRUE(run_called);
 }
diff --git a/base/files/file_path_watcher_unittest.cc b/base/files/file_path_watcher_unittest.cc
index 42121389..abc4bd44 100644
--- a/base/files/file_path_watcher_unittest.cc
+++ b/base/files/file_path_watcher_unittest.cc
@@ -21,12 +21,12 @@
 #include "base/files/scoped_temp_dir.h"
 #include "base/location.h"
 #include "base/macros.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/single_thread_task_runner.h"
 #include "base/stl_util.h"
 #include "base/strings/stringprintf.h"
 #include "base/synchronization/waitable_event.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/test/test_file_util.h"
 #include "base/test/test_timeouts.h"
 #include "base/threading/thread_task_runner_handle.h"
@@ -47,12 +47,12 @@
 
 class TestDelegate;
 
-// Aggregates notifications from the test delegates and breaks the message loop
+// Aggregates notifications from the test delegates and breaks the run loop
 // the test thread is waiting on once they all came in.
 class NotificationCollector
     : public base::RefCountedThreadSafe<NotificationCollector> {
  public:
-  NotificationCollector() : task_runner_(base::ThreadTaskRunnerHandle::Get()) {}
+  NotificationCollector() : task_runner_(ThreadTaskRunnerHandle::Get()) {}
 
   // Called from the file thread by the delegates.
   void OnChange(TestDelegate* delegate) {
@@ -143,7 +143,8 @@
  public:
   FilePathWatcherTest()
 #if defined(OS_POSIX)
-      : file_descriptor_watcher_(loop_.task_runner())
+      : scoped_task_environment_(
+            test::ScopedTaskEnvironment::MainThreadType::IO)
 #endif
   {
   }
@@ -204,10 +205,7 @@
 
   NotificationCollector* collector() { return collector_.get(); }
 
-  MessageLoopForIO loop_;
-#if defined(OS_POSIX)
-  FileDescriptorWatcher file_descriptor_watcher_;
-#endif
+  test::ScopedTaskEnvironment scoped_task_environment_;
 
   ScopedTempDir temp_dir_;
   scoped_refptr<NotificationCollector> collector_;
diff --git a/base/files/file_proxy_unittest.cc b/base/files/file_proxy_unittest.cc
index cb689db2f..27db2f6f 100644
--- a/base/files/file_proxy_unittest.cc
+++ b/base/files/file_proxy_unittest.cc
@@ -15,8 +15,8 @@
 #include "base/files/scoped_temp_dir.h"
 #include "base/macros.h"
 #include "base/memory/weak_ptr.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/threading/thread.h"
 #include "base/threading/thread_restrictions.h"
 #include "build/build_config.h"
@@ -27,7 +27,9 @@
 class FileProxyTest : public testing::Test {
  public:
   FileProxyTest()
-      : file_thread_("FileProxyTestFileThread"),
+      : scoped_task_environment_(
+            test::ScopedTaskEnvironment::MainThreadType::IO),
+        file_thread_("FileProxyTestFileThread"),
         error_(File::FILE_OK),
         bytes_written_(-1),
         weak_factory_(this) {}
@@ -93,7 +95,7 @@
   const FilePath TestPath() const { return dir_.GetPath().AppendASCII("test"); }
 
   ScopedTempDir dir_;
-  MessageLoopForIO message_loop_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
   Thread file_thread_;
 
   File::Error error_;
diff --git a/base/files/important_file_writer_unittest.cc b/base/files/important_file_writer_unittest.cc
index 5dddc71..39e6308 100644
--- a/base/files/important_file_writer_unittest.cc
+++ b/base/files/important_file_writer_unittest.cc
@@ -13,10 +13,10 @@
 #include "base/logging.h"
 #include "base/macros.h"
 #include "base/memory/ptr_util.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/single_thread_task_runner.h"
 #include "base/test/metrics/histogram_tester.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/threading/thread.h"
 #include "base/threading/thread_task_runner_handle.h"
 #include "base/time/time.h"
@@ -124,7 +124,7 @@
  protected:
   WriteCallbacksObserver write_callback_observer_;
   FilePath file_;
-  MessageLoop loop_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
 
  private:
   ScopedTempDir temp_dir_;
diff --git a/base/memory/memory_pressure_listener_unittest.cc b/base/memory/memory_pressure_listener_unittest.cc
index 87d5f4c..7c095ec 100644
--- a/base/memory/memory_pressure_listener_unittest.cc
+++ b/base/memory/memory_pressure_listener_unittest.cc
@@ -5,8 +5,8 @@
 #include "base/memory/memory_pressure_listener.h"
 
 #include "base/bind.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
+#include "base/test/scoped_task_environment.h"
 #include "testing/gmock/include/gmock/gmock.h"
 
 namespace base {
@@ -15,15 +15,17 @@
 
 class MemoryPressureListenerTest : public testing::Test {
  public:
+  MemoryPressureListenerTest()
+      : scoped_task_environment_(
+            test::ScopedTaskEnvironment::MainThreadType::UI) {}
+
   void SetUp() override {
-    message_loop_.reset(new MessageLoopForUI());
     listener_.reset(new MemoryPressureListener(
         Bind(&MemoryPressureListenerTest::OnMemoryPressure, Unretained(this))));
   }
 
   void TearDown() override {
     listener_.reset();
-    message_loop_.reset();
   }
 
  protected:
@@ -47,7 +49,7 @@
   MOCK_METHOD1(OnMemoryPressure,
                void(MemoryPressureListener::MemoryPressureLevel));
 
-  std::unique_ptr<MessageLoopForUI> message_loop_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
   std::unique_ptr<MemoryPressureListener> listener_;
 };
 
diff --git a/base/memory/memory_pressure_monitor_chromeos_unittest.cc b/base/memory/memory_pressure_monitor_chromeos_unittest.cc
index db715b4..8ac11334 100644
--- a/base/memory/memory_pressure_monitor_chromeos_unittest.cc
+++ b/base/memory/memory_pressure_monitor_chromeos_unittest.cc
@@ -6,9 +6,9 @@
 
 #include "base/macros.h"
 #include "base/memory/memory_pressure_listener.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/system/sys_info.h"
+#include "base/test/scoped_task_environment.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace base {
@@ -79,7 +79,8 @@
   if (base::SysInfo::IsRunningOnChromeOS())
     return;
 
-  base::MessageLoopForUI message_loop;
+  test::ScopedTaskEnvironment scoped_task_environment(
+      test::ScopedTaskEnvironment::MainThreadType::UI);
   std::unique_ptr<TestMemoryPressureMonitor> monitor(
       new TestMemoryPressureMonitor);
   std::unique_ptr<MemoryPressureListener> listener(
diff --git a/base/metrics/field_trial_unittest.cc b/base/metrics/field_trial_unittest.cc
index 0b861bb..dce2dd6 100644
--- a/base/metrics/field_trial_unittest.cc
+++ b/base/metrics/field_trial_unittest.cc
@@ -11,7 +11,6 @@
 #include "base/feature_list.h"
 #include "base/macros.h"
 #include "base/memory/ptr_util.h"
-#include "base/message_loop/message_loop.h"
 #include "base/metrics/field_trial_param_associator.h"
 #include "base/rand_util.h"
 #include "base/run_loop.h"
@@ -21,6 +20,7 @@
 #include "base/test/mock_entropy_provider.h"
 #include "base/test/multiprocess_test.h"
 #include "base/test/scoped_feature_list.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/test/test_shared_memory_util.h"
 #include "base/test/test_timeouts.h"
 #include "build/build_config.h"
@@ -107,7 +107,7 @@
   FieldTrialTest() : trial_list_(nullptr) {}
 
  private:
-  MessageLoop message_loop_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
   FieldTrialList trial_list_;
 
   DISALLOW_COPY_AND_ASSIGN(FieldTrialTest);
diff --git a/base/observer_list_threadsafe_unittest.cc b/base/observer_list_threadsafe_unittest.cc
index 3134fca7..00ca1cf 100644
--- a/base/observer_list_threadsafe_unittest.cc
+++ b/base/observer_list_threadsafe_unittest.cc
@@ -165,7 +165,7 @@
 }  // namespace
 
 TEST(ObserverListThreadSafeTest, BasicTest) {
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
 
   scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
       new ObserverListThreadSafe<Foo>);
@@ -194,7 +194,7 @@
 }
 
 TEST(ObserverListThreadSafeTest, RemoveObserver) {
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
 
   scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
       new ObserverListThreadSafe<Foo>);
@@ -237,7 +237,7 @@
 
   {
     // Add c when there's a sequence.
-    MessageLoop loop;
+    test::ScopedTaskEnvironment scoped_task_environment;
     observer_list->AddObserver(&c);
 
     observer_list->Notify(FROM_HERE, &Foo::Observe, 10);
@@ -266,7 +266,7 @@
   observer_list->RemoveObserver(&a);
 
   // Notifying should not fail but should also be a no-op.
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
   observer_list->AddObserver(&b);
   observer_list->Notify(FROM_HERE, &Foo::Observe, 30);
   RunLoop().RunUntilIdle();
@@ -297,7 +297,7 @@
 };
 
 TEST(ObserverListThreadSafeTest, RemoveMultipleObservers) {
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
   scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
       new ObserverListThreadSafe<Foo>);
 
@@ -320,7 +320,7 @@
 // observer threads will also trigger notifications to all observers.
 static void ThreadSafeObserverHarness(int num_threads,
                                       bool cross_thread_notifies) {
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
 
   scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
       new ObserverListThreadSafe<Foo>);
@@ -347,8 +347,8 @@
   ASSERT_EQ(static_cast<size_t>(num_threads), threaded_observer.size());
   ASSERT_EQ(static_cast<size_t>(num_threads), ready.size());
 
-  // This makes sure that threaded_observer has gotten to set loop_, so that we
-  // can call Quit() below safe-ish-ly.
+  // This makes sure that threaded_observer has gotten to set
+  // scoped_task_environment_, so that we can call Quit() below safe-ish-ly.
   for (int i = 0; i < num_threads; ++i)
     ready[i]->Wait();
 
@@ -385,14 +385,14 @@
   ThreadSafeObserverHarness(3, true);
 }
 
-TEST(ObserverListThreadSafeTest, OutlivesMessageLoop) {
-  MessageLoop* loop = new MessageLoop;
+TEST(ObserverListThreadSafeTest, OutlivesTaskEnvironment) {
+  Optional<test::ScopedTaskEnvironment> scoped_task_environment(in_place);
   scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
       new ObserverListThreadSafe<Foo>);
 
   Adder a(1);
   observer_list->AddObserver(&a);
-  delete loop;
+  scoped_task_environment.reset();
   // Test passes if we don't crash here.
   observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
 }
@@ -528,7 +528,7 @@
 
 // Same as ObserverListTest.Existing, but for ObserverListThreadSafe
 TEST(ObserverListThreadSafeTest, Existing) {
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
   scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
       new ObserverListThreadSafe<Foo>(ObserverListPolicy::EXISTING_ONLY));
   Adder a(1);
diff --git a/base/power_monitor/power_monitor_unittest.cc b/base/power_monitor/power_monitor_unittest.cc
index 85d069b..71fb260 100644
--- a/base/power_monitor/power_monitor_unittest.cc
+++ b/base/power_monitor/power_monitor_unittest.cc
@@ -2,10 +2,10 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "base/macros.h"
-#include "base/message_loop/message_loop.h"
 #include "base/power_monitor/power_monitor.h"
+#include "base/macros.h"
 #include "base/test/power_monitor_test_base.h"
+#include "base/test/scoped_task_environment.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace base {
@@ -23,7 +23,7 @@
   PowerMonitor* monitor() { return power_monitor_.get(); }
 
  private:
-  base::MessageLoop message_loop_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
   PowerMonitorTestSource* power_monitor_source_;
   std::unique_ptr<PowerMonitor> power_monitor_;
 
diff --git a/base/sequenced_task_runner_unittest.cc b/base/sequenced_task_runner_unittest.cc
index 4dcc7e5a..1a6c6e9 100644
--- a/base/sequenced_task_runner_unittest.cc
+++ b/base/sequenced_task_runner_unittest.cc
@@ -8,9 +8,10 @@
 
 #include "base/bind.h"
 #include "base/gtest_prod_util.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/threading/thread.h"
+#include "base/threading/thread_task_runner_handle.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace base {
@@ -46,19 +47,16 @@
   SequencedTaskRunnerTest() : foreign_thread_("foreign") {}
 
   void SetUp() override {
-    main_runner_ = message_loop_.task_runner();
-
     foreign_thread_.Start();
     foreign_runner_ = foreign_thread_.task_runner();
   }
 
-  scoped_refptr<SequencedTaskRunner> main_runner_;
   scoped_refptr<SequencedTaskRunner> foreign_runner_;
 
   Thread foreign_thread_;
 
  private:
-  MessageLoop message_loop_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
 
   DISALLOW_COPY_AND_ASSIGN(SequencedTaskRunnerTest);
 };
@@ -69,8 +67,8 @@
 TEST_F(SequencedTaskRunnerTest, OnTaskRunnerDeleterOnMainThread) {
   bool deleted_on_main_thread = false;
   SequenceBoundUniquePtr ptr(
-      new FlagOnDelete(&deleted_on_main_thread, main_runner_),
-      OnTaskRunnerDeleter(main_runner_));
+      new FlagOnDelete(&deleted_on_main_thread, ThreadTaskRunnerHandle::Get()),
+      OnTaskRunnerDeleter(ThreadTaskRunnerHandle::Get()));
   EXPECT_FALSE(deleted_on_main_thread);
   foreign_runner_->PostTask(
       FROM_HERE, BindOnce([](SequenceBoundUniquePtr) {}, std::move(ptr)));
@@ -86,7 +84,8 @@
 
 TEST_F(SequencedTaskRunnerTest, OnTaskRunnerDeleterTargetStoppedEarly) {
   bool deleted_on_main_thread = false;
-  FlagOnDelete* raw = new FlagOnDelete(&deleted_on_main_thread, main_runner_);
+  FlagOnDelete* raw =
+      new FlagOnDelete(&deleted_on_main_thread, ThreadTaskRunnerHandle::Get());
   SequenceBoundUniquePtr ptr(raw, OnTaskRunnerDeleter(foreign_runner_));
   EXPECT_FALSE(deleted_on_main_thread);
 
diff --git a/base/synchronization/waitable_event_watcher_unittest.cc b/base/synchronization/waitable_event_watcher_unittest.cc
index ec056eff..c1cb720 100644
--- a/base/synchronization/waitable_event_watcher_unittest.cc
+++ b/base/synchronization/waitable_event_watcher_unittest.cc
@@ -8,11 +8,12 @@
 #include "base/callback.h"
 #include "base/macros.h"
 #include "base/memory/ptr_util.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/synchronization/waitable_event.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/threading/platform_thread.h"
 #include "base/threading/sequenced_task_runner_handle.h"
+#include "base/threading/thread_task_runner_handle.h"
 #include "build/build_config.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -20,12 +21,12 @@
 
 namespace {
 
-// The message loops on which each waitable event timer should be tested.
-const MessageLoop::Type testing_message_loops[] = {
-  MessageLoop::TYPE_DEFAULT,
-  MessageLoop::TYPE_IO,
+// The main thread types on which each waitable event should be tested.
+const test::ScopedTaskEnvironment::MainThreadType testing_main_threads[] = {
+    test::ScopedTaskEnvironment::MainThreadType::DEFAULT,
+    test::ScopedTaskEnvironment::MainThreadType::IO,
 #if !defined(OS_IOS)  // iOS does not allow direct running of the UI loop.
-  MessageLoop::TYPE_UI,
+    test::ScopedTaskEnvironment::MainThreadType::UI,
 #endif
 };
 
@@ -48,10 +49,11 @@
 }  // namespace
 
 class WaitableEventWatcherTest
-    : public testing::TestWithParam<MessageLoop::Type> {};
+    : public testing::TestWithParam<
+          test::ScopedTaskEnvironment::MainThreadType> {};
 
 TEST_P(WaitableEventWatcherTest, BasicSignalManual) {
-  MessageLoop message_loop(GetParam());
+  test::ScopedTaskEnvironment scoped_task_environment(GetParam());
 
   // A manual-reset event that is not yet signaled.
   WaitableEvent event(WaitableEvent::ResetPolicy::MANUAL,
@@ -69,7 +71,7 @@
 }
 
 TEST_P(WaitableEventWatcherTest, BasicSignalAutomatic) {
-  MessageLoop message_loop(GetParam());
+  test::ScopedTaskEnvironment scoped_task_environment(GetParam());
 
   WaitableEvent event(WaitableEvent::ResetPolicy::AUTOMATIC,
                       WaitableEvent::InitialState::NOT_SIGNALED);
@@ -87,7 +89,7 @@
 }
 
 TEST_P(WaitableEventWatcherTest, BasicCancel) {
-  MessageLoop message_loop(GetParam());
+  test::ScopedTaskEnvironment scoped_task_environment(GetParam());
 
   // A manual-reset event that is not yet signaled.
   WaitableEvent event(WaitableEvent::ResetPolicy::MANUAL,
@@ -102,7 +104,7 @@
 }
 
 TEST_P(WaitableEventWatcherTest, CancelAfterSet) {
-  MessageLoop message_loop(GetParam());
+  test::ScopedTaskEnvironment scoped_task_environment(GetParam());
 
   // A manual-reset event that is not yet signaled.
   WaitableEvent event(WaitableEvent::ResetPolicy::MANUAL,
@@ -130,8 +132,8 @@
   EXPECT_EQ(1, counter);
 }
 
-TEST_P(WaitableEventWatcherTest, OutlivesMessageLoop) {
-  // Simulate a MessageLoop that dies before an WaitableEventWatcher.  This
+TEST_P(WaitableEventWatcherTest, OutlivesTaskEnvironment) {
+  // Simulate a task environment that dies before an WaitableEventWatcher.  This
   // ordinarily doesn't happen when people use the Thread class, but it can
   // happen when people use the Singleton pattern or atexit.
   WaitableEvent event(WaitableEvent::ResetPolicy::MANUAL,
@@ -139,7 +141,7 @@
   {
     std::unique_ptr<WaitableEventWatcher> watcher;
     {
-      MessageLoop message_loop(GetParam());
+      test::ScopedTaskEnvironment scoped_task_environment(GetParam());
       watcher = std::make_unique<WaitableEventWatcher>();
 
       watcher->StartWatching(&event, BindOnce(&QuitWhenSignaled),
@@ -149,7 +151,7 @@
 }
 
 TEST_P(WaitableEventWatcherTest, SignaledAtStartManual) {
-  MessageLoop message_loop(GetParam());
+  test::ScopedTaskEnvironment scoped_task_environment(GetParam());
 
   WaitableEvent event(WaitableEvent::ResetPolicy::MANUAL,
                       WaitableEvent::InitialState::SIGNALED);
@@ -164,7 +166,7 @@
 }
 
 TEST_P(WaitableEventWatcherTest, SignaledAtStartAutomatic) {
-  MessageLoop message_loop(GetParam());
+  test::ScopedTaskEnvironment scoped_task_environment(GetParam());
 
   WaitableEvent event(WaitableEvent::ResetPolicy::AUTOMATIC,
                       WaitableEvent::InitialState::SIGNALED);
@@ -180,7 +182,7 @@
 }
 
 TEST_P(WaitableEventWatcherTest, StartWatchingInCallback) {
-  MessageLoop message_loop(GetParam());
+  test::ScopedTaskEnvironment scoped_task_environment(GetParam());
 
   WaitableEvent event(WaitableEvent::ResetPolicy::MANUAL,
                       WaitableEvent::InitialState::NOT_SIGNALED);
@@ -204,7 +206,7 @@
 }
 
 TEST_P(WaitableEventWatcherTest, MultipleWatchersManual) {
-  MessageLoop message_loop(GetParam());
+  test::ScopedTaskEnvironment scoped_task_environment(GetParam());
 
   WaitableEvent event(WaitableEvent::ResetPolicy::MANUAL,
                       WaitableEvent::InitialState::NOT_SIGNALED);
@@ -239,7 +241,7 @@
 
 // Tests that only one async waiter gets called back for an auto-reset event.
 TEST_P(WaitableEventWatcherTest, MultipleWatchersAutomatic) {
-  MessageLoop message_loop(GetParam());
+  test::ScopedTaskEnvironment scoped_task_environment(GetParam());
 
   WaitableEvent event(WaitableEvent::ResetPolicy::AUTOMATIC,
                       WaitableEvent::InitialState::NOT_SIGNALED);
@@ -299,17 +301,18 @@
 // To help detect errors around deleting WaitableEventWatcher, an additional
 // bool parameter is used to test sleeping between watching and deletion.
 class WaitableEventWatcherDeletionTest
-    : public testing::TestWithParam<std::tuple<MessageLoop::Type, bool>> {};
+    : public testing::TestWithParam<
+          std::tuple<test::ScopedTaskEnvironment::MainThreadType, bool>> {};
 
 TEST_P(WaitableEventWatcherDeletionTest, DeleteUnder) {
-  MessageLoop::Type message_loop_type;
+  test::ScopedTaskEnvironment::MainThreadType main_thread_type;
   bool delay_after_delete;
-  std::tie(message_loop_type, delay_after_delete) = GetParam();
+  std::tie(main_thread_type, delay_after_delete) = GetParam();
 
   // Delete the WaitableEvent out from under the Watcher. This is explictly
   // allowed by the interface.
 
-  MessageLoop message_loop(message_loop_type);
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   {
     WaitableEventWatcher watcher;
@@ -334,13 +337,13 @@
 }
 
 TEST_P(WaitableEventWatcherDeletionTest, SignalAndDelete) {
-  MessageLoop::Type message_loop_type;
+  test::ScopedTaskEnvironment::MainThreadType main_thread_type;
   bool delay_after_delete;
-  std::tie(message_loop_type, delay_after_delete) = GetParam();
+  std::tie(main_thread_type, delay_after_delete) = GetParam();
 
   // Signal and immediately delete the WaitableEvent out from under the Watcher.
 
-  MessageLoop message_loop(message_loop_type);
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   {
     WaitableEventWatcher watcher;
@@ -371,13 +374,13 @@
 // Tests deleting the WaitableEventWatcher between signaling the event and
 // when the callback should be run.
 TEST_P(WaitableEventWatcherDeletionTest, DeleteWatcherBeforeCallback) {
-  MessageLoop::Type message_loop_type;
+  test::ScopedTaskEnvironment::MainThreadType main_thread_type;
   bool delay_after_delete;
-  std::tie(message_loop_type, delay_after_delete) = GetParam();
+  std::tie(main_thread_type, delay_after_delete) = GetParam();
 
-  MessageLoop message_loop(message_loop_type);
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
   scoped_refptr<SingleThreadTaskRunner> task_runner =
-      message_loop.task_runner();
+      ThreadTaskRunnerHandle::Get();
 
   // Flag used to esnure that the |watcher_callback| never runs.
   bool did_callback = false;
@@ -418,12 +421,11 @@
 
 INSTANTIATE_TEST_CASE_P(,
                         WaitableEventWatcherTest,
-                        testing::ValuesIn(testing_message_loops));
+                        testing::ValuesIn(testing_main_threads));
 
 INSTANTIATE_TEST_CASE_P(
     ,
     WaitableEventWatcherDeletionTest,
-    testing::Combine(testing::ValuesIn(testing_message_loops),
-                     testing::Bool()));
+    testing::Combine(testing::ValuesIn(testing_main_threads), testing::Bool()));
 
 }  // namespace base
diff --git a/base/system/system_monitor_unittest.cc b/base/system/system_monitor_unittest.cc
index f4ef68f..912a5d4 100644
--- a/base/system/system_monitor_unittest.cc
+++ b/base/system/system_monitor_unittest.cc
@@ -5,9 +5,9 @@
 #include "base/system/system_monitor.h"
 
 #include "base/macros.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/test/mock_devices_changed_observer.h"
+#include "base/test/scoped_task_environment.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -19,7 +19,7 @@
  protected:
   SystemMonitorTest() { system_monitor_.reset(new SystemMonitor); }
 
-  MessageLoop message_loop_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
   std::unique_ptr<SystemMonitor> system_monitor_;
 
  private:
diff --git a/base/task/cancelable_task_tracker_unittest.cc b/base/task/cancelable_task_tracker_unittest.cc
index c75adc4b..76032d94 100644
--- a/base/task/cancelable_task_tracker_unittest.cc
+++ b/base/task/cancelable_task_tracker_unittest.cc
@@ -12,10 +12,10 @@
 #include "base/logging.h"
 #include "base/memory/ref_counted.h"
 #include "base/memory/weak_ptr.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/single_thread_task_runner.h"
 #include "base/test/gtest_util.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/test/test_simple_task_runner.h"
 #include "base/threading/thread.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -37,7 +37,7 @@
 
  private:
   // Needed by CancelableTaskTracker methods.
-  MessageLoop message_loop_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
 };
 
 void AddFailureAt(const Location& location) {
diff --git a/base/task_runner_util_unittest.cc b/base/task_runner_util_unittest.cc
index c6d4997..9c1ed1f 100644
--- a/base/task_runner_util_unittest.cc
+++ b/base/task_runner_util_unittest.cc
@@ -8,8 +8,9 @@
 
 #include "base/bind.h"
 #include "base/location.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
+#include "base/test/scoped_task_environment.h"
+#include "base/threading/thread_task_runner_handle.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace base {
@@ -85,8 +86,8 @@
 TEST(TaskRunnerHelpersTest, PostTaskAndReplyWithResult) {
   int result = 0;
 
-  MessageLoop message_loop;
-  PostTaskAndReplyWithResult(message_loop.task_runner().get(), FROM_HERE,
+  test::ScopedTaskEnvironment scoped_task_environment;
+  PostTaskAndReplyWithResult(ThreadTaskRunnerHandle::Get().get(), FROM_HERE,
                              BindOnce(&ReturnFourtyTwo),
                              BindOnce(&StoreValue, &result));
 
@@ -98,8 +99,8 @@
 TEST(TaskRunnerHelpersTest, PostTaskAndReplyWithResultImplicitConvert) {
   double result = 0;
 
-  MessageLoop message_loop;
-  PostTaskAndReplyWithResult(message_loop.task_runner().get(), FROM_HERE,
+  test::ScopedTaskEnvironment scoped_task_environment;
+  PostTaskAndReplyWithResult(ThreadTaskRunnerHandle::Get().get(), FROM_HERE,
                              BindOnce(&ReturnFourtyTwo),
                              BindOnce(&StoreDoubleValue, &result));
 
@@ -112,8 +113,8 @@
   g_foo_destruct_count = 0;
   g_foo_free_count = 0;
 
-  MessageLoop message_loop;
-  PostTaskAndReplyWithResult(message_loop.task_runner().get(), FROM_HERE,
+  test::ScopedTaskEnvironment scoped_task_environment;
+  PostTaskAndReplyWithResult(ThreadTaskRunnerHandle::Get().get(), FROM_HERE,
                              BindOnce(&CreateFoo), BindOnce(&ExpectFoo));
 
   RunLoop().RunUntilIdle();
@@ -126,8 +127,8 @@
   g_foo_destruct_count = 0;
   g_foo_free_count = 0;
 
-  MessageLoop message_loop;
-  PostTaskAndReplyWithResult(message_loop.task_runner().get(), FROM_HERE,
+  test::ScopedTaskEnvironment scoped_task_environment;
+  PostTaskAndReplyWithResult(ThreadTaskRunnerHandle::Get().get(), FROM_HERE,
                              BindOnce(&CreateScopedFoo),
                              BindOnce(&ExpectScopedFoo));
 
@@ -141,10 +142,10 @@
      PostTaskAndReplyWithResultWithoutDefaultConstructor) {
   const int kSomeVal = 17;
 
-  MessageLoop message_loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
   int actual = 0;
   PostTaskAndReplyWithResult(
-      message_loop.task_runner().get(), FROM_HERE,
+      ThreadTaskRunnerHandle::Get().get(), FROM_HERE,
       BindOnce(&CreateFooWithoutDefaultConstructor, kSomeVal),
       BindOnce(&SaveFooWithoutDefaultConstructor, &actual));
 
diff --git a/base/threading/sequenced_task_runner_handle_unittest.cc b/base/threading/sequenced_task_runner_handle_unittest.cc
index de54d91..00d21b8 100644
--- a/base/threading/sequenced_task_runner_handle_unittest.cc
+++ b/base/threading/sequenced_task_runner_handle_unittest.cc
@@ -52,7 +52,7 @@
   base::test::ScopedTaskEnvironment scoped_task_environment_;
 };
 
-TEST_F(SequencedTaskRunnerHandleTest, FromMessageLoop) {
+TEST_F(SequencedTaskRunnerHandleTest, FromTaskEnvironment) {
   VerifyCurrentSequencedTaskRunner();
   RunLoop().RunUntilIdle();
 }
@@ -72,7 +72,7 @@
   scoped_task_environment_.RunUntilIdle();
 }
 
-TEST(SequencedTaskRunnerHandleTestWithoutMessageLoop, FromHandleInScope) {
+TEST(SequencedTaskRunnerHandleTestWithoutTaskEnvironment, FromHandleInScope) {
   scoped_refptr<SequencedTaskRunner> test_task_runner(new TestSimpleTaskRunner);
   EXPECT_FALSE(SequencedTaskRunnerHandle::IsSet());
   EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
diff --git a/base/timer/timer_unittest.cc b/base/timer/timer_unittest.cc
index 07b8002..a2cc476 100644
--- a/base/timer/timer_unittest.cc
+++ b/base/timer/timer_unittest.cc
@@ -33,11 +33,12 @@
 
 namespace {
 
-// The message loops on which each timer should be tested.
-const MessageLoop::Type testing_message_loops[] = {
-    MessageLoop::TYPE_DEFAULT, MessageLoop::TYPE_IO,
+// The main thread types on which each timer should be tested.
+const test::ScopedTaskEnvironment::MainThreadType testing_main_threads[] = {
+    test::ScopedTaskEnvironment::MainThreadType::DEFAULT,
+    test::ScopedTaskEnvironment::MainThreadType::IO,
 #if !defined(OS_IOS)  // iOS does not allow direct running of the UI loop.
-    MessageLoop::TYPE_UI,
+    test::ScopedTaskEnvironment::MainThreadType::UI,
 #endif
 };
 
@@ -109,7 +110,7 @@
     timer_->SetTaskRunner(std::move(task_runner));
 
     // Run() will be invoked on |task_runner| but |run_loop_|'s QuitClosure
-    // needs to run on this thread (where the MessageLoop lives).
+    // needs to run on this thread (where the task environment lives).
     quit_closure_ = BindOnce(IgnoreResult(&SequencedTaskRunner::PostTask),
                              SequencedTaskRunnerHandle::Get(), FROM_HERE,
                              run_loop_.QuitClosure());
@@ -197,8 +198,9 @@
 // Basic test with same setup as RunTest_OneShotTimers_Cancel below to confirm
 // that |did_run_a| would be signaled in that test if it wasn't for the
 // deletion.
-void RunTest_OneShotTimers(MessageLoop::Type message_loop_type) {
-  MessageLoop loop(message_loop_type);
+void RunTest_OneShotTimers(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   WaitableEvent did_run_a(WaitableEvent::ResetPolicy::MANUAL,
                           WaitableEvent::InitialState::NOT_SIGNALED);
@@ -213,8 +215,9 @@
   EXPECT_TRUE(did_run_a.IsSignaled());
 }
 
-void RunTest_OneShotTimers_Cancel(MessageLoop::Type message_loop_type) {
-  MessageLoop loop(message_loop_type);
+void RunTest_OneShotTimers_Cancel(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   WaitableEvent did_run_a(WaitableEvent::ResetPolicy::MANUAL,
                           WaitableEvent::InitialState::NOT_SIGNALED);
@@ -234,26 +237,29 @@
   EXPECT_FALSE(did_run_a.IsSignaled());
 }
 
-void RunTest_OneShotSelfDeletingTimer(MessageLoop::Type message_loop_type) {
-  MessageLoop loop(message_loop_type);
+void RunTest_OneShotSelfDeletingTimer(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   OneShotSelfDeletingTimerTester f;
   f.Start();
   f.WaitAndConfirmTimerFiredAfterDelay();
 }
 
-void RunTest_RepeatingTimer(MessageLoop::Type message_loop_type,
-                            const TimeDelta& delay) {
-  MessageLoop loop(message_loop_type);
+void RunTest_RepeatingTimer(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type,
+    const TimeDelta& delay) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   RepeatingTimerTester f(nullptr, delay);
   f.Start();
   f.WaitAndConfirmTimerFiredRepeatedlyAfterDelay();
 }
 
-void RunTest_RepeatingTimer_Cancel(MessageLoop::Type message_loop_type,
-                                   const TimeDelta& delay) {
-  MessageLoop loop(message_loop_type);
+void RunTest_RepeatingTimer_Cancel(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type,
+    const TimeDelta& delay) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   WaitableEvent did_run_a(WaitableEvent::ResetPolicy::MANUAL,
                           WaitableEvent::InitialState::NOT_SIGNALED);
@@ -288,8 +294,9 @@
   bool signaled_ = false;
 };
 
-void RunTest_DelayTimer_NoCall(MessageLoop::Type message_loop_type) {
-  MessageLoop loop(message_loop_type);
+void RunTest_DelayTimer_NoCall(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   // If Delay is never called, the timer shouldn't go off.
   DelayTimerTarget target;
@@ -303,8 +310,9 @@
   ASSERT_FALSE(target.signaled());
 }
 
-void RunTest_DelayTimer_OneCall(MessageLoop::Type message_loop_type) {
-  MessageLoop loop(message_loop_type);
+void RunTest_DelayTimer_OneCall(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   DelayTimerTarget target;
   DelayTimer timer(FROM_HERE, TimeDelta::FromMilliseconds(1), &target,
@@ -332,8 +340,9 @@
   DelayTimerTarget* const target_;
 };
 
-void RunTest_DelayTimer_Reset(MessageLoop::Type message_loop_type) {
-  MessageLoop loop(message_loop_type);
+void RunTest_DelayTimer_Reset(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   // If Delay is never called, the timer shouldn't go off.
   DelayTimerTarget target;
@@ -363,8 +372,9 @@
   }
 };
 
-void RunTest_DelayTimer_Deleted(MessageLoop::Type message_loop_type) {
-  MessageLoop loop(message_loop_type);
+void RunTest_DelayTimer_Deleted(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   DelayTimerFatalTarget target;
 
@@ -382,33 +392,31 @@
 }  // namespace
 
 //-----------------------------------------------------------------------------
-// Each test is run against each type of MessageLoop.  That way we are sure
+// Each test is run against each type of main thread.  That way we are sure
 // that timers work properly in all configurations.
 
-TEST(TimerTest, OneShotTimers) {
-  for (auto i : testing_message_loops) {
-    RunTest_OneShotTimers(i);
-  }
+class TimerTestWithThreadType
+    : public testing::TestWithParam<
+          test::ScopedTaskEnvironment::MainThreadType> {};
+
+TEST_P(TimerTestWithThreadType, OneShotTimers) {
+  RunTest_OneShotTimers(GetParam());
 }
 
-TEST(TimerTest, OneShotTimers_Cancel) {
-  for (auto i : testing_message_loops) {
-    RunTest_OneShotTimers_Cancel(i);
-  }
+TEST_P(TimerTestWithThreadType, OneShotTimers_Cancel) {
+  RunTest_OneShotTimers_Cancel(GetParam());
 }
 
 // If underline timer does not handle properly, we will crash or fail
 // in full page heap environment.
-TEST(TimerTest, OneShotSelfDeletingTimer) {
-  for (auto i : testing_message_loops) {
-    RunTest_OneShotSelfDeletingTimer(i);
-  }
+TEST_P(TimerTestWithThreadType, OneShotSelfDeletingTimer) {
+  RunTest_OneShotSelfDeletingTimer(GetParam());
 }
 
 TEST(TimerTest, OneShotTimer_CustomTaskRunner) {
-  // A MessageLoop is required for the timer events on the other thread to
+  // A task environment is required for the timer events on the other thread to
   // communicate back to the Timer under test.
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
 
   Thread other_thread("OneShotTimer_CustomTaskRunner");
   other_thread.Start();
@@ -423,109 +431,89 @@
   f.WaitAndConfirmTimerFiredAfterDelay();
   EXPECT_TRUE(did_run.IsSignaled());
 
-  // |f| should already have communicated back to this |loop| before invoking
-  // Run() and as such this thread should already be aware that |f| is no longer
-  // running.
-  EXPECT_TRUE(loop.IsIdleForTesting());
+  // |f| should already have communicated back to this main thread before
+  // invoking Run() and as such this thread should already be aware that |f| is
+  // no longer running.
+  EXPECT_FALSE(scoped_task_environment.MainThreadHasPendingTask());
   EXPECT_FALSE(f.IsRunning());
 }
 
 TEST(TimerTest, OneShotTimerWithTickClock) {
-  scoped_refptr<TestMockTimeTaskRunner> task_runner(
-      new TestMockTimeTaskRunner(Time::Now(), TimeTicks::Now()));
-  MessageLoop message_loop;
-  message_loop.SetTaskRunner(task_runner);
+  test::ScopedTaskEnvironment scoped_task_environment(
+      test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME);
   Receiver receiver;
-  OneShotTimer timer(task_runner->GetMockTickClock());
+  OneShotTimer timer(scoped_task_environment.GetMockTickClock());
   timer.Start(FROM_HERE, TimeDelta::FromSeconds(1),
               BindOnce(&Receiver::OnCalled, Unretained(&receiver)));
-  task_runner->FastForwardBy(TimeDelta::FromSeconds(1));
+  scoped_task_environment.FastForwardBy(TimeDelta::FromSeconds(1));
   EXPECT_TRUE(receiver.WasCalled());
 }
 
-TEST(TimerTest, RepeatingTimer) {
-  for (auto i : testing_message_loops) {
-    RunTest_RepeatingTimer(i, TimeDelta::FromMilliseconds(10));
-  }
+TEST_P(TimerTestWithThreadType, RepeatingTimer) {
+  RunTest_RepeatingTimer(GetParam(), TimeDelta::FromMilliseconds(10));
 }
 
-TEST(TimerTest, RepeatingTimer_Cancel) {
-  for (auto i : testing_message_loops) {
-    RunTest_RepeatingTimer_Cancel(i, TimeDelta::FromMilliseconds(10));
-  }
+TEST_P(TimerTestWithThreadType, RepeatingTimer_Cancel) {
+  RunTest_RepeatingTimer_Cancel(GetParam(), TimeDelta::FromMilliseconds(10));
 }
 
-TEST(TimerTest, RepeatingTimerZeroDelay) {
-  for (auto i : testing_message_loops) {
-    RunTest_RepeatingTimer(i, TimeDelta::FromMilliseconds(0));
-  }
+TEST_P(TimerTestWithThreadType, RepeatingTimerZeroDelay) {
+  RunTest_RepeatingTimer(GetParam(), TimeDelta::FromMilliseconds(0));
 }
 
-TEST(TimerTest, RepeatingTimerZeroDelay_Cancel) {
-  for (auto i : testing_message_loops) {
-    RunTest_RepeatingTimer_Cancel(i, TimeDelta::FromMilliseconds(0));
-  }
+TEST_P(TimerTestWithThreadType, RepeatingTimerZeroDelay_Cancel) {
+  RunTest_RepeatingTimer_Cancel(GetParam(), TimeDelta::FromMilliseconds(0));
 }
 
 TEST(TimerTest, RepeatingTimerWithTickClock) {
-  scoped_refptr<TestMockTimeTaskRunner> task_runner(
-      new TestMockTimeTaskRunner(Time::Now(), TimeTicks::Now()));
-  MessageLoop message_loop;
-  message_loop.SetTaskRunner(task_runner);
+  test::ScopedTaskEnvironment scoped_task_environment(
+      test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME);
   Receiver receiver;
   const int expected_times_called = 10;
-  RepeatingTimer timer(task_runner->GetMockTickClock());
+  RepeatingTimer timer(scoped_task_environment.GetMockTickClock());
   timer.Start(FROM_HERE, TimeDelta::FromSeconds(1),
               BindRepeating(&Receiver::OnCalled, Unretained(&receiver)));
-  task_runner->FastForwardBy(TimeDelta::FromSeconds(expected_times_called));
+  scoped_task_environment.FastForwardBy(
+      TimeDelta::FromSeconds(expected_times_called));
   timer.Stop();
   EXPECT_EQ(expected_times_called, receiver.TimesCalled());
 }
 
-TEST(TimerTest, DelayTimer_NoCall) {
-  for (auto i : testing_message_loops) {
-    RunTest_DelayTimer_NoCall(i);
-  }
+TEST_P(TimerTestWithThreadType, DelayTimer_NoCall) {
+  RunTest_DelayTimer_NoCall(GetParam());
 }
 
-TEST(TimerTest, DelayTimer_OneCall) {
-  for (auto i : testing_message_loops) {
-    RunTest_DelayTimer_OneCall(i);
-  }
+TEST_P(TimerTestWithThreadType, DelayTimer_OneCall) {
+  RunTest_DelayTimer_OneCall(GetParam());
 }
 
 // It's flaky on the buildbot, http://crbug.com/25038.
-TEST(TimerTest, DISABLED_DelayTimer_Reset) {
-  for (auto i : testing_message_loops) {
-    RunTest_DelayTimer_Reset(i);
-  }
+TEST_P(TimerTestWithThreadType, DISABLED_DelayTimer_Reset) {
+  RunTest_DelayTimer_Reset(GetParam());
 }
 
-TEST(TimerTest, DelayTimer_Deleted) {
-  for (auto i : testing_message_loops) {
-    RunTest_DelayTimer_Deleted(i);
-  }
+TEST_P(TimerTestWithThreadType, DelayTimer_Deleted) {
+  RunTest_DelayTimer_Deleted(GetParam());
 }
 
 TEST(TimerTest, DelayTimerWithTickClock) {
-  scoped_refptr<TestMockTimeTaskRunner> task_runner(
-      new TestMockTimeTaskRunner(Time::Now(), TimeTicks::Now()));
-  MessageLoop message_loop;
-  message_loop.SetTaskRunner(task_runner);
+  test::ScopedTaskEnvironment scoped_task_environment(
+      test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME);
   Receiver receiver;
   DelayTimer timer(FROM_HERE, TimeDelta::FromSeconds(1), &receiver,
-                   &Receiver::OnCalled, task_runner->GetMockTickClock());
-  task_runner->FastForwardBy(TimeDelta::FromMilliseconds(999));
+                   &Receiver::OnCalled,
+                   scoped_task_environment.GetMockTickClock());
+  scoped_task_environment.FastForwardBy(TimeDelta::FromMilliseconds(999));
   EXPECT_FALSE(receiver.WasCalled());
   timer.Reset();
-  task_runner->FastForwardBy(TimeDelta::FromMilliseconds(999));
+  scoped_task_environment.FastForwardBy(TimeDelta::FromMilliseconds(999));
   EXPECT_FALSE(receiver.WasCalled());
   timer.Reset();
-  task_runner->FastForwardBy(TimeDelta::FromSeconds(1));
+  scoped_task_environment.FastForwardBy(TimeDelta::FromSeconds(1));
   EXPECT_TRUE(receiver.WasCalled());
 }
 
-TEST(TimerTest, MessageLoopShutdown) {
+TEST(TimerTest, TaskEnvironmentShutdown) {
   // This test is designed to verify that shutdown of the
   // message loop does not cause crashes if there were pending
   // timers not yet fired.  It may only trigger exceptions
@@ -538,10 +526,10 @@
     OneShotTimerTesterBase c(&did_run);
     OneShotTimerTesterBase d(&did_run);
     {
-      MessageLoop loop;
+      test::ScopedTaskEnvironment scoped_task_environment;
       a.Start();
       b.Start();
-    }  // MessageLoop destructs by falling out of scope.
+    }  // Task environment destructs by falling out of scope.
   }  // OneShotTimers destruct.  SHOULD NOT CRASH, of course.
 
   EXPECT_FALSE(did_run.IsSignaled());
@@ -575,20 +563,20 @@
   DISALLOW_COPY_AND_ASSIGN(OneShotSelfOwningTimerTester);
 };
 
-TEST(TimerTest, MessageLoopShutdownSelfOwningTimer) {
-  // This test verifies that shutdown of the message loop does not cause crashes
-  // if there is a pending timer not yet fired and |Timer::user_task_| owns the
-  // timer. The test may only trigger exceptions if debug heap checking is
-  // enabled.
+TEST(TimerTest, TaskEnvironmentShutdownSelfOwningTimer) {
+  // This test verifies that shutdown of the task environment does not cause
+  // crashes if there is a pending timer not yet fired and |Timer::user_task_|
+  // owns the timer. The test may only trigger exceptions if debug heap checking
+  // is enabled.
 
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
   scoped_refptr<OneShotSelfOwningTimerTester> tester =
       new OneShotSelfOwningTimerTester();
 
   std::move(tester)->StartTimer();
   // |Timer::user_task_| owns sole reference to |tester|.
 
-  // MessageLoop destructs by falling out of scope. SHOULD NOT CRASH.
+  // Task environment destructs by falling out of scope. SHOULD NOT CRASH.
 }
 
 void TimerTestCallback() {
@@ -596,7 +584,7 @@
 
 TEST(TimerTest, NonRepeatIsRunning) {
   {
-    MessageLoop loop;
+    test::ScopedTaskEnvironment scoped_task_environment;
     OneShotTimer timer;
     EXPECT_FALSE(timer.IsRunning());
     timer.Start(FROM_HERE, TimeDelta::FromDays(1),
@@ -608,7 +596,7 @@
 
   {
     RetainingOneShotTimer timer;
-    MessageLoop loop;
+    test::ScopedTaskEnvironment scoped_task_environment;
     EXPECT_FALSE(timer.IsRunning());
     timer.Start(FROM_HERE, TimeDelta::FromDays(1),
                 BindRepeating(&TimerTestCallback));
@@ -621,10 +609,10 @@
   }
 }
 
-TEST(TimerTest, NonRepeatMessageLoopDeath) {
+TEST(TimerTest, NonRepeatTaskEnvironmentDeath) {
   OneShotTimer timer;
   {
-    MessageLoop loop;
+    test::ScopedTaskEnvironment scoped_task_environment;
     EXPECT_FALSE(timer.IsRunning());
     timer.Start(FROM_HERE, TimeDelta::FromDays(1),
                 BindOnce(&TimerTestCallback));
@@ -634,7 +622,7 @@
 }
 
 TEST(TimerTest, RetainRepeatIsRunning) {
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
   RepeatingTimer timer(FROM_HERE, TimeDelta::FromDays(1),
                        BindRepeating(&TimerTestCallback));
   EXPECT_FALSE(timer.IsRunning());
@@ -647,7 +635,7 @@
 }
 
 TEST(TimerTest, RetainNonRepeatIsRunning) {
-  MessageLoop loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
   RetainingOneShotTimer timer(FROM_HERE, TimeDelta::FromDays(1),
                               BindRepeating(&TimerTestCallback));
   EXPECT_FALSE(timer.IsRunning());
@@ -686,7 +674,7 @@
 TEST(TimerTest, ContinuationStopStart) {
   {
     ClearAllCallbackHappened();
-    MessageLoop loop;
+    test::ScopedTaskEnvironment scoped_task_environment;
     OneShotTimer timer;
     timer.Start(FROM_HERE, TimeDelta::FromMilliseconds(10),
                 BindOnce(&SetCallbackHappened1));
@@ -702,7 +690,7 @@
 TEST(TimerTest, ContinuationReset) {
   {
     ClearAllCallbackHappened();
-    MessageLoop loop;
+    test::ScopedTaskEnvironment scoped_task_environment;
     OneShotTimer timer;
     timer.Start(FROM_HERE, TimeDelta::FromMilliseconds(10),
                 BindOnce(&SetCallbackHappened1));
@@ -714,6 +702,10 @@
   }
 }
 
+INSTANTIATE_TEST_CASE_P(,
+                        TimerTestWithThreadType,
+                        testing::ValuesIn(testing_main_threads));
+
 namespace {
 
 // Fixture for tests requiring ScopedTaskEnvironment. Includes a WaitableEvent
@@ -771,7 +763,7 @@
     Signal();
   }
 
-  base::test::ScopedTaskEnvironment scoped_task_environment_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
   WaitableEvent event_;
   std::unique_ptr<OneShotTimer> timer_;
 
@@ -798,7 +790,7 @@
 
   // Spin the loop so that the delayed task fires on it, which will forward it
   // to |task_runner|. And since the Timer's task is one that posts back to this
-  // MessageLoop to quit, we finally unblock.
+  // thread to quit, we finally unblock.
   run_loop_.Run();
 
   // Timer will be destroyed on this thread.
diff --git a/base/trace_event/blame_context_unittest.cc b/base/trace_event/blame_context_unittest.cc
index f628115..ad7bad5 100644
--- a/base/trace_event/blame_context_unittest.cc
+++ b/base/trace_event/blame_context_unittest.cc
@@ -5,7 +5,7 @@
 #include "base/trace_event/blame_context.h"
 
 #include "base/json/json_writer.h"
-#include "base/message_loop/message_loop.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/test/trace_event_analyzer.h"
 #include "base/trace_event/traced_value.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -58,7 +58,7 @@
 
 class BlameContextTest : public testing::Test {
  protected:
-  MessageLoop loop_;
+  test::ScopedTaskEnvironment scoped_task_environment_;
 };
 
 TEST_F(BlameContextTest, EnterAndLeave) {
diff --git a/base/trace_event/trace_event_system_stats_monitor_unittest.cc b/base/trace_event/trace_event_system_stats_monitor_unittest.cc
index 52a05ba9..8688d71 100644
--- a/base/trace_event/trace_event_system_stats_monitor_unittest.cc
+++ b/base/trace_event/trace_event_system_stats_monitor_unittest.cc
@@ -8,8 +8,9 @@
 #include <string>
 
 #include "base/macros.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
+#include "base/test/scoped_task_environment.h"
+#include "base/threading/thread_task_runner_handle.h"
 #include "base/trace_event/trace_event_impl.h"
 #include "build/build_config.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -32,14 +33,14 @@
 //////////////////////////////////////////////////////////////////////////////
 
 TEST_F(TraceSystemStatsMonitorTest, TraceEventSystemStatsMonitor) {
-  MessageLoop message_loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
 
   // Start with no observers of the TraceLog.
   EXPECT_EQ(0u, TraceLog::GetInstance()->GetObserverCountForTest());
 
   // Creating a system stats monitor adds it to the TraceLog observer list.
   std::unique_ptr<TraceEventSystemStatsMonitor> system_stats_monitor(
-      new TraceEventSystemStatsMonitor(message_loop.task_runner()));
+      new TraceEventSystemStatsMonitor(ThreadTaskRunnerHandle::Get()));
   EXPECT_EQ(1u, TraceLog::GetInstance()->GetObserverCountForTest());
   EXPECT_TRUE(
       TraceLog::GetInstance()->HasEnabledStateObserver(
diff --git a/base/win/object_watcher_unittest.cc b/base/win/object_watcher_unittest.cc
index 5aa3891..bbec192 100644
--- a/base/win/object_watcher_unittest.cc
+++ b/base/win/object_watcher_unittest.cc
@@ -5,9 +5,10 @@
 #include "base/win/object_watcher.h"
 
 #include <process.h>
+#include <windows.h>
 
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
+#include "base/test/scoped_task_environment.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace base {
@@ -32,8 +33,9 @@
   int* counter_;
 };
 
-void RunTest_BasicSignal(MessageLoop::Type message_loop_type) {
-  MessageLoop message_loop(message_loop_type);
+void RunTest_BasicSignal(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   ObjectWatcher watcher;
   EXPECT_FALSE(watcher.IsWatching());
@@ -55,8 +57,9 @@
   CloseHandle(event);
 }
 
-void RunTest_BasicCancel(MessageLoop::Type message_loop_type) {
-  MessageLoop message_loop(message_loop_type);
+void RunTest_BasicCancel(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   ObjectWatcher watcher;
 
@@ -72,8 +75,9 @@
   CloseHandle(event);
 }
 
-void RunTest_CancelAfterSet(MessageLoop::Type message_loop_type) {
-  MessageLoop message_loop(message_loop_type);
+void RunTest_CancelAfterSet(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   ObjectWatcher watcher;
 
@@ -101,8 +105,9 @@
   CloseHandle(event);
 }
 
-void RunTest_SignalBeforeWatch(MessageLoop::Type message_loop_type) {
-  MessageLoop message_loop(message_loop_type);
+void RunTest_SignalBeforeWatch(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   ObjectWatcher watcher;
 
@@ -119,15 +124,16 @@
   CloseHandle(event);
 }
 
-void RunTest_OutlivesMessageLoop(MessageLoop::Type message_loop_type) {
-  // Simulate a MessageLoop that dies before an ObjectWatcher.  This ordinarily
-  // doesn't happen when people use the Thread class, but it can happen when
-  // people use the Singleton pattern or atexit.
+void RunTest_OutlivesTaskEnvironment(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  // Simulate a task environment that dies before an ObjectWatcher.  This
+  // ordinarily doesn't happen when people use the Thread class, but it can
+  // happen when people use the Singleton pattern or atexit.
   HANDLE event = CreateEvent(NULL, TRUE, FALSE, NULL);  // not signaled
   {
     ObjectWatcher watcher;
     {
-      MessageLoop message_loop(message_loop_type);
+      test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
       QuitDelegate delegate;
       watcher.StartWatchingOnce(event, &delegate);
@@ -153,8 +159,9 @@
   int iterations_;
 };
 
-void RunTest_ExecuteMultipleTimes(MessageLoop::Type message_loop_type) {
-  MessageLoop message_loop(message_loop_type);
+void RunTest_ExecuteMultipleTimes(
+    test::ScopedTaskEnvironment::MainThreadType main_thread_type) {
+  test::ScopedTaskEnvironment scoped_task_environment(main_thread_type);
 
   ObjectWatcher watcher;
   EXPECT_FALSE(watcher.IsWatching());
@@ -182,39 +189,44 @@
 //-----------------------------------------------------------------------------
 
 TEST(ObjectWatcherTest, BasicSignal) {
-  RunTest_BasicSignal(MessageLoop::TYPE_DEFAULT);
-  RunTest_BasicSignal(MessageLoop::TYPE_IO);
-  RunTest_BasicSignal(MessageLoop::TYPE_UI);
+  RunTest_BasicSignal(test::ScopedTaskEnvironment::MainThreadType::DEFAULT);
+  RunTest_BasicSignal(test::ScopedTaskEnvironment::MainThreadType::IO);
+  RunTest_BasicSignal(test::ScopedTaskEnvironment::MainThreadType::UI);
 }
 
 TEST(ObjectWatcherTest, BasicCancel) {
-  RunTest_BasicCancel(MessageLoop::TYPE_DEFAULT);
-  RunTest_BasicCancel(MessageLoop::TYPE_IO);
-  RunTest_BasicCancel(MessageLoop::TYPE_UI);
+  RunTest_BasicCancel(test::ScopedTaskEnvironment::MainThreadType::DEFAULT);
+  RunTest_BasicCancel(test::ScopedTaskEnvironment::MainThreadType::IO);
+  RunTest_BasicCancel(test::ScopedTaskEnvironment::MainThreadType::UI);
 }
 
 TEST(ObjectWatcherTest, CancelAfterSet) {
-  RunTest_CancelAfterSet(MessageLoop::TYPE_DEFAULT);
-  RunTest_CancelAfterSet(MessageLoop::TYPE_IO);
-  RunTest_CancelAfterSet(MessageLoop::TYPE_UI);
+  RunTest_CancelAfterSet(test::ScopedTaskEnvironment::MainThreadType::DEFAULT);
+  RunTest_CancelAfterSet(test::ScopedTaskEnvironment::MainThreadType::IO);
+  RunTest_CancelAfterSet(test::ScopedTaskEnvironment::MainThreadType::UI);
 }
 
 TEST(ObjectWatcherTest, SignalBeforeWatch) {
-  RunTest_SignalBeforeWatch(MessageLoop::TYPE_DEFAULT);
-  RunTest_SignalBeforeWatch(MessageLoop::TYPE_IO);
-  RunTest_SignalBeforeWatch(MessageLoop::TYPE_UI);
+  RunTest_SignalBeforeWatch(
+      test::ScopedTaskEnvironment::MainThreadType::DEFAULT);
+  RunTest_SignalBeforeWatch(test::ScopedTaskEnvironment::MainThreadType::IO);
+  RunTest_SignalBeforeWatch(test::ScopedTaskEnvironment::MainThreadType::UI);
 }
 
-TEST(ObjectWatcherTest, OutlivesMessageLoop) {
-  RunTest_OutlivesMessageLoop(MessageLoop::TYPE_DEFAULT);
-  RunTest_OutlivesMessageLoop(MessageLoop::TYPE_IO);
-  RunTest_OutlivesMessageLoop(MessageLoop::TYPE_UI);
+TEST(ObjectWatcherTest, OutlivesTaskEnvironment) {
+  RunTest_OutlivesTaskEnvironment(
+      test::ScopedTaskEnvironment::MainThreadType::DEFAULT);
+  RunTest_OutlivesTaskEnvironment(
+      test::ScopedTaskEnvironment::MainThreadType::IO);
+  RunTest_OutlivesTaskEnvironment(
+      test::ScopedTaskEnvironment::MainThreadType::UI);
 }
 
 TEST(ObjectWatcherTest, ExecuteMultipleTimes) {
-  RunTest_ExecuteMultipleTimes(MessageLoop::TYPE_DEFAULT);
-  RunTest_ExecuteMultipleTimes(MessageLoop::TYPE_IO);
-  RunTest_ExecuteMultipleTimes(MessageLoop::TYPE_UI);
+  RunTest_ExecuteMultipleTimes(
+      test::ScopedTaskEnvironment::MainThreadType::DEFAULT);
+  RunTest_ExecuteMultipleTimes(test::ScopedTaskEnvironment::MainThreadType::IO);
+  RunTest_ExecuteMultipleTimes(test::ScopedTaskEnvironment::MainThreadType::UI);
 }
 
 }  // namespace win
diff --git a/base/win/registry_unittest.cc b/base/win/registry_unittest.cc
index 5a18ffa..ee960cf9 100644
--- a/base/win/registry_unittest.cc
+++ b/base/win/registry_unittest.cc
@@ -5,6 +5,7 @@
 #include "base/win/registry.h"
 
 #include <stdint.h>
+#include <windows.h>
 
 #include <cstring>
 #include <vector>
@@ -12,9 +13,9 @@
 #include "base/bind.h"
 #include "base/compiler_specific.h"
 #include "base/macros.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/stl_util.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/win/windows_version.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -378,7 +379,7 @@
 TEST_F(RegistryTest, ChangeCallback) {
   RegKey key;
   TestChangeDelegate delegate;
-  MessageLoop message_loop;
+  test::ScopedTaskEnvironment scoped_task_environment;
 
   std::wstring foo_key(kRootKey);
   foo_key += L"\\Foo";