Bug 1239870 - Part 5: Switch over mtransport tests to mozilla gtests. r=bwc
☠☠ backed out by 22424f6eeb30 ☠ ☠
authorEric Rahm <erahm@mozilla.com>
Tue, 09 Feb 2016 10:02:40 -0800
changeset 324140 1d385d4f195d718b74177e7f10ebf1df87496dfe
parent 324139 ceb3e1ee7dda59c010b172a8c13b872a4fa65220
child 324141 ab0347657e25475064c29a193d5505075500901a
push id1128
push userjlund@mozilla.com
push dateWed, 01 Jun 2016 01:31:59 +0000
treeherdermozilla-release@fe0d30de989d [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersbwc
bugs1239870
milestone47.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1239870 - Part 5: Switch over mtransport tests to mozilla gtests. r=bwc This converts the individual cppunit gtests into the combined mozilla gtest which has access to xpcom internals. The build file is simplified to reflect this change, individual main functions are removed, and duplicate symbols are removed.
media/mtransport/test/TestSyncRunnable.cpp
media/mtransport/test/buffered_stun_socket_unittest.cpp
media/mtransport/test/gtest_ringbuffer_dumper.h
media/mtransport/test/gtest_utils.h
media/mtransport/test/ice_unittest.cpp
media/mtransport/test/moz.build
media/mtransport/test/mtransport_test_utils.h
media/mtransport/test/multi_tcp_socket_unittest.cpp
media/mtransport/test/nrappkit_unittest.cpp
media/mtransport/test/proxy_tunnel_socket_unittest.cpp
media/mtransport/test/rlogringbuffer_unittest.cpp
media/mtransport/test/runnable_utils_unittest.cpp
media/mtransport/test/sctp_unittest.cpp
media/mtransport/test/simpletokenbucket_unittest.cpp
media/mtransport/test/sockettransportservice_unittest.cpp
media/mtransport/test/test_nr_socket_unittest.cpp
media/mtransport/test/transport_unittests.cpp
media/mtransport/test/turn_unittest.cpp
media/webrtc/signaling/test/jsep_session_unittest.cpp
media/webrtc/signaling/test/jsep_track_unittest.cpp
media/webrtc/signaling/test/mediapipeline_unittest.cpp
media/webrtc/signaling/test/sdp_unittests.cpp
--- a/media/mtransport/test/TestSyncRunnable.cpp
+++ b/media/mtransport/test/TestSyncRunnable.cpp
@@ -54,24 +54,8 @@ TEST_F(TestSyncRunnable, TestDispatch)
 }
 
 TEST_F(TestSyncRunnable, TestDispatchStatic)
 {
   RefPtr<TestRunnable> r(new TestRunnable());
   SyncRunnable::DispatchToThread(gThread, r);
   ASSERT_TRUE(r->ran());
 }
-
-
-#include "mtransport_test_utils.h"
-MtransportTestUtils *test_utils;
-
-int main(int argc, char **argv)
-{
-  test_utils = new MtransportTestUtils();
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-
-  delete test_utils;
-  return rv;
-}
--- a/media/mtransport/test/buffered_stun_socket_unittest.cpp
+++ b/media/mtransport/test/buffered_stun_socket_unittest.cpp
@@ -18,47 +18,48 @@ extern "C" {
 #include "nr_api.h"
 #include "nr_socket.h"
 #include "nr_socket_buffered_stun.h"
 #include "transport_addr.h"
 #include "stun.h"
 }
 
 #include "databuffer.h"
-#include "mtransport_test_utils.h"
 #include "dummysocket.h"
 
 #include "nr_socket_prsock.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
 using namespace mozilla;
-MtransportTestUtils *test_utils;
 
 static uint8_t kStunMessage[] = {
   0x00, 0x01, 0x00, 0x08, 0x21, 0x12, 0xa4, 0x42,
   0x9b, 0x90, 0xbe, 0x2c, 0xae, 0x1a, 0x0c, 0xa8,
   0xa0, 0xd6, 0x8b, 0x08, 0x80, 0x28, 0x00, 0x04,
   0xdb, 0x35, 0x5f, 0xaa
 };
 static size_t kStunMessageLen = sizeof(kStunMessage);
 
-class BufferedStunSocketTest : public ::testing::Test {
+class BufferedStunSocketTest : public MtransportTest {
  public:
   BufferedStunSocketTest()
-      : dummy_(nullptr),
-        test_socket_(nullptr) {}
+      : MtransportTest(),
+        dummy_(nullptr),
+        test_socket_(nullptr) { }
 
   ~BufferedStunSocketTest() {
     nr_socket_destroy(&test_socket_);
   }
 
   void SetUp() {
+    MtransportTest::SetUp();
+
     RefPtr<DummySocket> dummy(new DummySocket());
 
     int r = nr_socket_buffered_stun_create(
         dummy->get_nr_socket(),
         kStunMessageLen,
         TURN_TCP_FRAMING,
         &test_socket_);
     ASSERT_EQ(0, r);
@@ -290,25 +291,8 @@ TEST_F(BufferedStunSocketTest, TestRecei
   size_t len;
   nr_transport_addr addr;
 
   int r = nr_socket_recvfrom(test_socket_,
                              tmp, kStunMessageLen - 1, &len, 0,
                              &addr);
   ASSERT_EQ(R_BAD_DATA, r);
 }
-
-
-
-int main(int argc, char **argv)
-{
-  test_utils = new MtransportTestUtils();
-  NSS_NoDB_Init(nullptr);
-  NSS_SetDomesticPolicy();
-
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-
-  delete test_utils;
-  return rv;
-}
--- a/media/mtransport/test/gtest_ringbuffer_dumper.h
+++ b/media/mtransport/test/gtest_ringbuffer_dumper.h
@@ -8,18 +8,18 @@
 
 #ifndef gtest_ringbuffer_dumper_h__
 #define gtest_ringbuffer_dumper_h__
 
 #include "mozilla/SyncRunnable.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
-#include "gtest_utils.h"
 
+#include "mtransport_test_utils.h"
 #include "runnable_utils.h"
 #include "rlogringbuffer.h"
 
 using mozilla::RLogRingBuffer;
 using mozilla::WrapRunnable;
 
 namespace test {
 class RingbufferDumper : public ::testing::EmptyTestEventListener {
--- a/media/mtransport/test/gtest_utils.h
+++ b/media/mtransport/test/gtest_utils.h
@@ -43,16 +43,17 @@
 
 #include "nspr.h"
 #include "prinrval.h"
 #include "prthread.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 
+#include "gtest_ringbuffer_dumper.h"
 #include "mtransport_test_utils.h"
 #include "nss.h"
 #include "ssl.h"
 
 extern "C" {
 #include "registry.h"
 #include "transport_addr.h"
 }
@@ -92,24 +93,27 @@ extern "C" {
   } while(0)
 
 #define ASSERT_EQ_WAIT(expected, actual, timeout) \
   do { \
     WAIT(expected == actual, timeout); \
     ASSERT_EQ(expected, actual); \
   } while(0)
 
+using test::RingbufferDumper;
+
 class MtransportTest : public ::testing::Test {
 public:
   MtransportTest()
     : test_utils_(nullptr)
+    , dumper_(nullptr)
   {
   }
 
-  void SetUp() {
+  void SetUp() override {
     test_utils_ = new MtransportTestUtils();
     NSS_NoDB_Init(nullptr);
     NSS_SetDomesticPolicy();
 
     NR_reg_init(NR_REG_MODE_LOCAL);
 
     // Attempt to load env vars used by tests.
     GetEnvironment("TURN_SERVER_ADDRESS", turn_server_);
@@ -130,19 +134,27 @@ public:
       // cpp unit-tests, but is not presently.
       stun_server_address_ = "";
       stun_server_hostname_ = "";
       turn_server_ = "";
     }
 
     // Some tests are flaky and need to check if they're supposed to run.
     webrtc_enabled_ = CheckEnvironmentFlag("MOZ_WEBRTC_TESTS");
+
+    ::testing::TestEventListeners& listeners =
+        ::testing::UnitTest::GetInstance()->listeners();
+
+    dumper_ = new RingbufferDumper(test_utils_);
+    listeners.Append(dumper_);
   }
 
-  void TearDown() {
+  void TearDown() override {
+    ::testing::UnitTest::GetInstance()->listeners().Release(dumper_);
+    delete dumper_;
     delete test_utils_;
   }
 
   void GetEnvironment(const char* aVar, std::string& out) {
     char* value = getenv(aVar);
     if (value) {
       out = value;
     }
@@ -173,16 +185,17 @@ public:
         "Set TURN_SERVER_ADDRESS, TURN_SERVER_USER, and TURN_SERVER_PASSWORD\n"
         "environment variables to run this test\n");
     }
 
     return !configured;
   }
 
   MtransportTestUtils* test_utils_;
+  RingbufferDumper* dumper_;
 
   std::string turn_server_;
   std::string turn_user_;
   std::string turn_password_;
   std::string stun_server_address_;
   std::string stun_server_hostname_;
 
   bool webrtc_enabled_;
--- a/media/mtransport/test/ice_unittest.cpp
+++ b/media/mtransport/test/ice_unittest.cpp
@@ -16,54 +16,52 @@
 
 #include "sigslot.h"
 
 #include "logging.h"
 #include "nspr.h"
 #include "nss.h"
 #include "ssl.h"
 
+#include "mozilla/Preferences.h"
 #include "mozilla/Scoped.h"
 #include "nsThreadUtils.h"
 #include "nsXPCOM.h"
 
 #include "nricectx.h"
 #include "nricemediastream.h"
 #include "nriceresolverfake.h"
 #include "nriceresolver.h"
 #include "nrinterfaceprioritizer.h"
-#include "mtransport_test_utils.h"
 #include "gtest_ringbuffer_dumper.h"
 #include "rlogringbuffer.h"
 #include "runnable_utils.h"
 #include "stunserver.h"
 #include "nr_socket_prsock.h"
 #include "test_nr_socket.h"
 #include "ice_ctx.h"
-// TODO(bcampen@mozilla.com): Big fat hack since the build system doesn't give
-// us a clean way to add object files to a single executable.
-#include "stunserver.cpp"
 #include "stun_udp_socket_filter.h"
 #include "mozilla/net/DNS.h"
 
 #include "ice_ctx.h"
 #include "ice_peer_ctx.h"
 #include "ice_media_stream.h"
 
 extern "C" {
+#include "async_timer.h"
 #include "r_data.h"
 #include "util.h"
 }
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
+
 using namespace mozilla;
-MtransportTestUtils *test_utils;
 
 bool stream_added = false;
 
 static unsigned int kDefaultTimeout = 7000;
 
 //TODO(nils@mozilla.com): This should get replaced with some non-external
 //solution like discussed in bug 860775.
 const std::string kDefaultStunServerHostname(
@@ -72,24 +70,116 @@ const std::string kBogusStunServerHostna
     (char *)"stun-server-nonexistent.invalid");
 const uint16_t kDefaultStunServerPort=3478;
 const std::string kBogusIceCandidate(
     (char *)"candidate:0 2 UDP 2113601790 192.168.178.20 50769 typ");
 
 const std::string kUnreachableHostIceCandidate(
     (char *)"candidate:0 1 UDP 2113601790 192.168.178.20 50769 typ host");
 
-std::string g_stun_server_address;
-std::string g_stun_server_hostname(kDefaultStunServerHostname);
-std::string g_turn_server;
-std::string g_turn_user;
-std::string g_turn_password;
-
 namespace {
 
+// DNS resolution helper code
+static std::string
+Resolve(const std::string& fqdn, int address_family)
+{
+  struct addrinfo hints;
+  memset(&hints, 0, sizeof(hints));
+  hints.ai_family = address_family;
+  hints.ai_protocol = IPPROTO_UDP;
+  struct addrinfo *res;
+  int err = getaddrinfo(fqdn.c_str(), nullptr, &hints, &res);
+  if (err) {
+    std::cerr << "Error in getaddrinfo: " << err << std::endl;
+    return "";
+  }
+
+  char str_addr[64] = {0};
+  switch (res->ai_family) {
+    case AF_INET:
+      inet_ntop(
+          AF_INET,
+          &reinterpret_cast<struct sockaddr_in*>(res->ai_addr)->sin_addr,
+          str_addr,
+          sizeof(str_addr));
+      break;
+    case AF_INET6:
+      inet_ntop(
+          AF_INET6,
+          &reinterpret_cast<struct sockaddr_in6*>(res->ai_addr)->sin6_addr,
+          str_addr,
+          sizeof(str_addr));
+      break;
+    default:
+      std::cerr << "Got unexpected address family in DNS lookup: "
+                << res->ai_family << std::endl;
+      return "";
+  }
+
+  if (!strlen(str_addr)) {
+    std::cerr << "inet_ntop failed" << std::endl;
+  }
+
+  return str_addr;
+}
+
+class StunTest : public MtransportTest {
+public:
+  StunTest() : MtransportTest() {
+    stun_server_hostname_ = kDefaultStunServerHostname;
+  }
+
+  void SetUp() override {
+    MtransportTest::SetUp();
+
+    // If only a STUN server FQDN was provided, look up its IP address for the
+    // address-only tests.
+    if (stun_server_address_.empty() && !stun_server_hostname_.empty()) {
+      stun_server_address_ = Resolve(stun_server_hostname_, AF_INET);
+    }
+
+    RLogRingBuffer::CreateInstance();
+
+    // Make sure NrIceCtx is in a testable state.
+    test_utils_->sts_target()->Dispatch(
+        WrapRunnableNM(&NrIceCtx::internal_DeinitializeGlobal),
+        NS_DISPATCH_SYNC);
+
+    test_utils_->sts_target()->Dispatch(
+        WrapRunnableNM(&TestStunServer::GetInstance, AF_INET),
+                       NS_DISPATCH_SYNC);
+    test_utils_->sts_target()->Dispatch(
+        WrapRunnableNM(&TestStunServer::GetInstance, AF_INET6),
+                       NS_DISPATCH_SYNC);
+
+    test_utils_->sts_target()->Dispatch(
+        WrapRunnableNM(&TestStunTcpServer::GetInstance, AF_INET),
+                       NS_DISPATCH_SYNC);
+    test_utils_->sts_target()->Dispatch(
+        WrapRunnableNM(&TestStunTcpServer::GetInstance, AF_INET6),
+                       NS_DISPATCH_SYNC);
+  }
+
+  void TearDown() override {
+    test_utils_->sts_target()->Dispatch(
+        WrapRunnableNM(&NrIceCtx::internal_DeinitializeGlobal),
+        NS_DISPATCH_SYNC);
+
+    test_utils_->sts_target()->Dispatch(
+        WrapRunnableNM(&TestStunServer::ShutdownInstance), NS_DISPATCH_SYNC);
+
+    test_utils_->sts_target()->Dispatch(
+        WrapRunnableNM(&TestStunTcpServer::ShutdownInstance), NS_DISPATCH_SYNC);
+
+    RLogRingBuffer::DestroyInstance();
+
+    MtransportTest::TearDown();
+  }
+};
+
 enum TrickleMode { TRICKLE_NONE, TRICKLE_SIMULATE, TRICKLE_REAL };
 
 const unsigned int ICE_TEST_PEER_OFFERER = (1 << 0);
 const unsigned int ICE_TEST_PEER_ALLOW_LOOPBACK = (1 << 1);
 const unsigned int ICE_TEST_PEER_ENABLED_TCP = (1 << 2);
 const unsigned int ICE_TEST_PEER_ALLOW_LINK_LOCAL = (1 << 3);
 const unsigned int ICE_TEST_PEER_HIDE_NON_DEFAULT = (1 << 4);
 
@@ -213,30 +303,32 @@ class IceCandidatePairCompare {
 };
 
 class IceTestPeer;
 
 class SchedulableTrickleCandidate {
   public:
     SchedulableTrickleCandidate(IceTestPeer *peer,
                                 size_t stream,
-                                const std::string &candidate) :
+                                const std::string &candidate,
+                                MtransportTestUtils* utils) :
       peer_(peer),
       stream_(stream),
       candidate_(candidate),
-      timer_handle_(nullptr) {
+      timer_handle_(nullptr),
+      test_utils_(utils) {
     }
 
     ~SchedulableTrickleCandidate() {
       if (timer_handle_)
         NR_async_timer_cancel(timer_handle_);
     }
 
     void Schedule(unsigned int ms) {
-      test_utils->sts_target()->Dispatch(
+      test_utils_->sts_target()->Dispatch(
           WrapRunnable(this, &SchedulableTrickleCandidate::Schedule_s, ms),
           NS_DISPATCH_SYNC);
     }
 
     void Schedule_s(unsigned int ms) {
       MOZ_ASSERT(!timer_handle_);
       NR_ASYNC_TIMER_SET(ms, Trickle_cb, this, &timer_handle_);
     }
@@ -271,25 +363,27 @@ class SchedulableTrickleCandidate {
       return candidate_.find("typ relay") != std::string::npos;
     }
 
   private:
     IceTestPeer *peer_;
     size_t stream_;
     std::string candidate_;
     void *timer_handle_;
+    MtransportTestUtils* test_utils_;
 
     DISALLOW_COPY_ASSIGN(SchedulableTrickleCandidate);
 };
 
 class IceTestPeer : public sigslot::has_slots<> {
  public:
   // TODO(ekr@rtfm.com): Convert to flags when NrIceCtx::Create() does.
   // Bug 1193437.
-  IceTestPeer(const std::string& name, bool offerer,
+  IceTestPeer(const std::string& name, MtransportTestUtils* utils,
+              bool offerer,
               bool allow_loopback = false, bool enable_tcp = true,
               bool allow_link_local = false, bool hide_non_default = false) :
       name_(name),
       ice_ctx_(NrIceCtx::Create(name, offerer, allow_loopback,
                                 enable_tcp, allow_link_local, hide_non_default)),
       streams_(),
       candidates_(),
       gathering_complete_(false),
@@ -303,31 +397,32 @@ class IceTestPeer : public sigslot::has_
       remote_(nullptr),
       candidate_filter_(nullptr),
       expected_local_type_(NrIceCandidate::ICE_HOST),
       expected_local_transport_(kNrIceTransportUdp),
       expected_remote_type_(NrIceCandidate::ICE_HOST),
       trickle_mode_(TRICKLE_NONE),
       trickled_(0),
       simulate_ice_lite_(false),
-      nat_(new TestNat) {
+      nat_(new TestNat),
+      test_utils_(utils) {
     ice_ctx_->SignalGatheringStateChange.connect(
         this,
         &IceTestPeer::GatheringStateChange);
     ice_ctx_->SignalConnectionStateChange.connect(
         this,
         &IceTestPeer::ConnectionStateChange);
 
     int r = ice_ctx_->SetNat(nat_);
     (void)r;
     MOZ_ASSERT(!r);
   }
 
   ~IceTestPeer() {
-    test_utils->sts_target()->Dispatch(WrapRunnable(this,
+    test_utils_->sts_target()->Dispatch(WrapRunnable(this,
                                                     &IceTestPeer::Shutdown),
         NS_DISPATCH_SYNC);
 
     // Give the ICE destruction callback time to fire before
     // we destroy the resolver.
     PR_Sleep(1000);
   }
 
@@ -345,28 +440,28 @@ class IceTestPeer : public sigslot::has_
     stream->SignalCandidate.connect(this, &IceTestPeer::CandidateInitialized);
     stream->SignalReady.connect(this, &IceTestPeer::StreamReady);
     stream->SignalFailed.connect(this, &IceTestPeer::StreamFailed);
     stream->SignalPacketReceived.connect(this, &IceTestPeer::PacketReceived);
   }
 
   void AddStream(int components)
   {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnable(this, &IceTestPeer::AddStream_s, components),
         NS_DISPATCH_SYNC);
   }
 
   void RemoveStream_s(size_t index) {
     streams_[index] = nullptr;
     ice_ctx_->SetStream(index, nullptr);
   }
 
   void RemoveStream(size_t index) {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnable(this, &IceTestPeer::RemoveStream_s, index),
         NS_DISPATCH_SYNC);
   }
 
   void SetStunServer(const std::string addr, uint16_t port,
                      const char* transport = kNrIceTransportUdp) {
     if (addr.empty()) {
       // Happens when MOZ_DISABLE_NONLOCAL_CONNECTIONS is set
@@ -408,18 +503,18 @@ class IceTestPeer : public sigslot::has_
     turn_servers.push_back(*server);
     ASSERT_TRUE(NS_SUCCEEDED(ice_ctx_->SetTurnServers(turn_servers)));
   }
 
   void SetTurnServers(const std::vector<NrIceTurnServer> servers) {
     ASSERT_TRUE(NS_SUCCEEDED(ice_ctx_->SetTurnServers(servers)));
   }
 
-  void SetFakeResolver(const std::string& ip = g_stun_server_address,
-                       const std::string& fqdn = g_stun_server_hostname) {
+  void SetFakeResolver(const std::string& ip,
+                       const std::string& fqdn) {
     ASSERT_TRUE(NS_SUCCEEDED(dns_resolver_->Init()));
     if (!ip.empty() && !fqdn.empty()) {
       PRNetAddr addr;
       PRStatus status = PR_StringToNetAddr(ip.c_str(), &addr);
       addr.inet.port = kDefaultStunServerPort;
       ASSERT_EQ(PR_SUCCESS, status);
       fake_resolver_.SetAddr(fqdn, addr);
     }
@@ -431,17 +526,17 @@ class IceTestPeer : public sigslot::has_
     ASSERT_TRUE(NS_SUCCEEDED(dns_resolver_->Init()));
     ASSERT_TRUE(NS_SUCCEEDED(ice_ctx_->SetResolver(
         dns_resolver_->AllocateResolver())));
   }
 
   void Gather() {
     nsresult res;
 
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&res, ice_ctx_, &NrIceCtx::StartGathering),
         NS_DISPATCH_SYNC);
 
     ASSERT_TRUE(NS_SUCCEEDED(res));
   }
 
   void UseNat() {
     nat_->enabled_ = true;
@@ -470,17 +565,17 @@ class IceTestPeer : public sigslot::has_
     }
     return attrs;
   }
 
   std::vector<std::string> GetCandidates(size_t stream) {
     std::vector<std::string> v;
 
     RUN_ON_THREAD(
-        test_utils->sts_target(),
+        test_utils_->sts_target(),
         WrapRunnableRet(&v, this, &IceTestPeer::GetCandidates_s, stream));
 
     return v;
   }
 
   std::string FilterCandidate(const std::string& candidate) {
     if (candidate_filter_) {
       return candidate_filter_(candidate);
@@ -556,17 +651,17 @@ class IceTestPeer : public sigslot::has_
       EXPECT_TRUE(false) << "No such stream " << stream;
       return false;
     }
     return streams_[stream]->state() == NrIceMediaStream::ICE_OPEN;
   }
   bool is_ready(size_t stream)
   {
     bool result;
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&result, this, &IceTestPeer::is_ready_s, stream),
         NS_DISPATCH_SYNC);
     return result;
   }
   bool ice_complete() { return ice_complete_; }
   bool ice_reached_checking() { return ice_reached_checking_; }
   size_t received() { return received_; }
   size_t sent() { return sent_; }
@@ -615,17 +710,17 @@ class IceTestPeer : public sigslot::has_
       // Now start checks
       res = ice_ctx_->StartChecks();
       ASSERT_TRUE(NS_SUCCEEDED(res));
     }
   }
 
   void Connect(IceTestPeer *remote, TrickleMode trickle_mode,
                bool start = true) {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnable(
             this, &IceTestPeer::Connect_s, remote, trickle_mode, start),
         NS_DISPATCH_SYNC);
   }
 
   void SimulateTrickle(size_t stream) {
     std::cerr << "Doing trickle for stream " << stream << std::endl;
     // If we are in trickle deferred mode, now trickle in the candidates
@@ -650,17 +745,18 @@ class IceTestPeer : public sigslot::has_
   std::vector<SchedulableTrickleCandidate*>& ControlTrickle(size_t stream) {
     std::cerr << "Doing controlled trickle for stream " << stream << std::endl;
 
     std::vector<std::string> candidates =
       remote_->GetCandidates(stream);
 
     for (size_t j=0; j<candidates.size(); j++) {
       controlled_trickle_candidates_[stream].push_back(
-          new SchedulableTrickleCandidate(this, stream, candidates[j]));
+          new SchedulableTrickleCandidate(
+              this, stream, candidates[j], test_utils_));
     }
 
     return controlled_trickle_candidates_[stream];
   }
 
   nsresult TrickleCandidate_s(const std::string &candidate, size_t stream) {
     if (!streams_[stream]) {
       // stream might have gone away before the trickle timer popped
@@ -781,23 +877,23 @@ class IceTestPeer : public sigslot::has_
           delete local;
           delete remote;
         }
       }
     }
   }
 
   void DumpAndCheckActiveCandidates() {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
       WrapRunnable(this, &IceTestPeer::DumpAndCheckActiveCandidates_s),
       NS_DISPATCH_SYNC);
   }
 
   void Close() {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
       WrapRunnable(ice_ctx_, &NrIceCtx::destroy_peer_ctx),
       NS_DISPATCH_SYNC);
   }
 
   void Shutdown() {
     for (auto s = controlled_trickle_candidates_.begin();
          s != controlled_trickle_candidates_.end();
          ++s) {
@@ -818,17 +914,17 @@ class IceTestPeer : public sigslot::has_
   {
     remote_ = nullptr;
   }
 
   void StartChecks() {
     nsresult res;
 
     // Now start checks
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&res, ice_ctx_, &NrIceCtx::StartChecks),
         NS_DISPATCH_SYNC);
     ASSERT_TRUE(NS_SUCCEEDED(res));
   }
 
   // Handle events
   void GatheringStateChange(NrIceCtx* ctx,
                             NrIceCtx::GatheringState state) {
@@ -896,17 +992,17 @@ class IceTestPeer : public sigslot::has_
     }
 
     return streams_[stream_index]->GetCandidatePairs(pairs);
   }
 
   nsresult GetCandidatePairs(size_t stream_index,
                              std::vector<NrIceCandidatePair>* pairs) {
     nsresult v;
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&v, this,
                         &IceTestPeer::GetCandidatePairs_s,
                         stream_index,
                         pairs),
         NS_DISPATCH_SYNC);
     return v;
   }
 
@@ -1081,55 +1177,55 @@ class IceTestPeer : public sigslot::has_
     std::vector<std::string> attributes;
 
     attributes.push_back(candidate);
     streams_[i]->ParseAttributes(attributes);
   }
 
   void ParseCandidate(size_t i, const std::string& candidate)
   {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnable(this,
                         &IceTestPeer::ParseCandidate_s,
                         i,
                         candidate),
         NS_DISPATCH_SYNC);
   }
 
   void DisableComponent_s(size_t stream, int component_id) {
     ASSERT_LT(stream, streams_.size());
     ASSERT_TRUE(streams_[stream]) << "No such stream " << stream;
     nsresult res = streams_[stream]->DisableComponent(component_id);
     ASSERT_TRUE(NS_SUCCEEDED(res));
   }
 
   void DisableComponent(size_t stream, int component_id)
   {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnable(this,
                         &IceTestPeer::DisableComponent_s,
                         stream,
                         component_id),
         NS_DISPATCH_SYNC);
   }
 
   int trickled() { return trickled_; }
 
   void SetControlling(NrIceCtx::Controlling controlling) {
     nsresult res;
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&res, ice_ctx_,
                         &NrIceCtx::SetControlling,
                         controlling),
         NS_DISPATCH_SYNC);
     ASSERT_TRUE(NS_SUCCEEDED(res));
   }
 
   void SetTiebreaker(uint64_t tiebreaker) {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnable(this,
                      &IceTestPeer::SetTiebreaker_s,
                      tiebreaker),
         NS_DISPATCH_SYNC);
   }
 
   void SetTiebreaker_s(uint64_t tiebreaker) {
     ice_ctx_->peer()->tiebreaker = tiebreaker;
@@ -1138,17 +1234,17 @@ class IceTestPeer : public sigslot::has_
   void SimulateIceLite() {
     simulate_ice_lite_ = true;
     SetControlling(NrIceCtx::ICE_CONTROLLED);
   }
 
   nsresult GetDefaultCandidate(unsigned int stream, NrIceCandidate* cand) {
     nsresult rv;
 
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&rv, this,
                         &IceTestPeer::GetDefaultCandidate_s,
                         stream, cand),
         NS_DISPATCH_SYNC);
 
     return rv;
   }
 
@@ -1177,54 +1273,52 @@ class IceTestPeer : public sigslot::has_
   NrIceCandidate::Type expected_local_type_;
   std::string expected_local_transport_;
   NrIceCandidate::Type expected_remote_type_;
   std::string expected_remote_addr_;
   TrickleMode trickle_mode_;
   int trickled_;
   bool simulate_ice_lite_;
   RefPtr<mozilla::TestNat> nat_;
+  MtransportTestUtils* test_utils_;
 };
 
 void SchedulableTrickleCandidate::Trickle() {
   timer_handle_ = nullptr;
   nsresult res = peer_->TrickleCandidate_s(candidate_, stream_);
   ASSERT_TRUE(NS_SUCCEEDED(res));
 }
 
-class IceGatherTest : public ::testing::Test {
+class IceGatherTest : public StunTest {
  public:
-  void SetUp() {
-    test_utils->sts_target()->Dispatch(
+  void SetUp() override {
+    StunTest::SetUp();
+
+    Preferences::SetInt("media.peerconnection.ice.tcp_so_sock_count", 3);
+
+    test_utils_->sts_target()->Dispatch(
         WrapRunnable(TestStunServer::GetInstance(AF_INET),
                      &TestStunServer::Reset),
         NS_DISPATCH_SYNC);
     if (TestStunServer::GetInstance(AF_INET6)) {
-      test_utils->sts_target()->Dispatch(
+      test_utils_->sts_target()->Dispatch(
           WrapRunnable(TestStunServer::GetInstance(AF_INET6),
                        &TestStunServer::Reset),
           NS_DISPATCH_SYNC);
     }
   }
 
-  void TearDown() {
+  void TearDown() override {
     peer_ = nullptr;
-
-    test_utils->sts_target()->Dispatch(WrapRunnable(this,
-                                                    &IceGatherTest::TearDown_s),
-                                       NS_DISPATCH_SYNC);
-  }
-
-  void TearDown_s() {
-    NrIceCtx::internal_DeinitializeGlobal();
+    StunTest::TearDown();
   }
 
   void EnsurePeer(const unsigned int flags = ICE_TEST_PEER_OFFERER) {
     if (!peer_) {
-      peer_ = new IceTestPeer("P1",
+      peer_ = new IceTestPeer("P1", test_utils_,
                               flags & ICE_TEST_PEER_OFFERER,
                               flags & ICE_TEST_PEER_ALLOW_LOOPBACK,
                               flags & ICE_TEST_PEER_ENABLED_TCP,
                               flags & ICE_TEST_PEER_ALLOW_LINK_LOCAL,
                               flags & ICE_TEST_PEER_HIDE_NON_DEFAULT);
       peer_->AddStream(1);
     }
   }
@@ -1355,60 +1449,56 @@ class IceGatherTest : public ::testing::
       std::cerr << "Candidate: " << c << std::endl;
     }
   }
 
  protected:
   mozilla::ScopedDeletePtr<IceTestPeer> peer_;
 };
 
-class IceConnectTest : public ::testing::Test {
+class IceConnectTest : public StunTest {
  public:
   IceConnectTest() :
     initted_(false),
     use_nat_(false),
     filtering_type_(TestNat::ENDPOINT_INDEPENDENT),
     mapping_type_(TestNat::ENDPOINT_INDEPENDENT),
     block_udp_(false) {}
 
-  void SetUp() {
+  void SetUp() override {
+    StunTest::SetUp();
+
     nsresult rv;
     target_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
     ASSERT_TRUE(NS_SUCCEEDED(rv));
   }
 
-  void TearDown() {
+  void TearDown() override {
     p1_ = nullptr;
     p2_ = nullptr;
 
-    test_utils->sts_target()->Dispatch(WrapRunnable(this,
-                                                    &IceConnectTest::TearDown_s),
-                                       NS_DISPATCH_SYNC);
-  }
-
-  void TearDown_s() {
-    NrIceCtx::internal_DeinitializeGlobal();
+    StunTest::TearDown();
   }
 
   void AddStream(const std::string& name, int components) {
     Init(false, false);
     p1_->AddStream(components);
     p2_->AddStream(components);
   }
 
   void RemoveStream(size_t index) {
     p1_->RemoveStream(index);
     p2_->RemoveStream(index);
   }
 
   void Init(bool allow_loopback, bool enable_tcp, bool default_only = false) {
     if (!initted_) {
-      p1_ = new IceTestPeer("P1", true, allow_loopback,
+      p1_ = new IceTestPeer("P1", test_utils_, true, allow_loopback,
                             enable_tcp, false, default_only);
-      p2_ = new IceTestPeer("P2", false, allow_loopback,
+      p2_ = new IceTestPeer("P2", test_utils_, false, allow_loopback,
                             enable_tcp, false, default_only);
     }
     initted_ = true;
   }
 
   bool Gather(unsigned int waitTime = kDefaultTimeout,
               bool setupStunServers = true) {
     Init(false, false);
@@ -1426,19 +1516,19 @@ class IceConnectTest : public ::testing:
       p2_->SetFilteringType(filtering_type_);
       p1_->SetMappingType(mapping_type_);
       p2_->SetMappingType(mapping_type_);
       p1_->SetBlockUdp(block_udp_);
       p2_->SetBlockUdp(block_udp_);
     } else if (setupStunServers) {
       std::vector<NrIceStunServer> stun_servers;
 
-      stun_servers.push_back(*NrIceStunServer::Create(g_stun_server_address,
+      stun_servers.push_back(*NrIceStunServer::Create(stun_server_address_,
                                                       kDefaultStunServerPort, kNrIceTransportUdp));
-      stun_servers.push_back(*NrIceStunServer::Create(g_stun_server_address,
+      stun_servers.push_back(*NrIceStunServer::Create(stun_server_address_,
                                                       kDefaultStunServerPort, kNrIceTransportTcp));
 
       p1_->SetStunServers(stun_servers);
       p2_->SetStunServers(stun_servers);
     }
 
     p1_->Gather();
     p2_->Gather();
@@ -1581,28 +1671,28 @@ class IceConnectTest : public ::testing:
 
   void CloseP1() {
     p1_->Close();
   }
 
   void ConnectThenDelete() {
     p2_->Connect(p1_, TRICKLE_NONE, false);
     p1_->Connect(p2_, TRICKLE_NONE, true);
-    test_utils->sts_target()->Dispatch(WrapRunnable(this,
+    test_utils_->sts_target()->Dispatch(WrapRunnable(this,
                                                     &IceConnectTest::CloseP1),
                                        NS_DISPATCH_SYNC);
     p2_->StartChecks();
 
     // Wait to see if we crash
     PR_Sleep(PR_MillisecondsToInterval(kDefaultTimeout));
   }
 
   void SendReceive() {
     //    p1_->Send(2);
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnable(p1_.get(),
                      &IceTestPeer::SendPacket, 0, 1,
                      reinterpret_cast<const unsigned char *>("TEST"), 4),
         NS_DISPATCH_SYNC);
     ASSERT_EQ(1u, p1_->sent());
     ASSERT_TRUE_WAIT(p2_->received() == 1, 1000);
   }
 
@@ -1612,17 +1702,17 @@ class IceConnectTest : public ::testing:
   mozilla::ScopedDeletePtr<IceTestPeer> p1_;
   mozilla::ScopedDeletePtr<IceTestPeer> p2_;
   bool use_nat_;
   TestNat::NatBehavior filtering_type_;
   TestNat::NatBehavior mapping_type_;
   bool block_udp_;
 };
 
-class PrioritizerTest : public ::testing::Test {
+class PrioritizerTest : public StunTest {
  public:
   PrioritizerTest():
     prioritizer_(nullptr) {}
 
   ~PrioritizerTest() {
     if (prioritizer_) {
       nr_interface_prioritizer_destroy(&prioritizer_);
     }
@@ -1660,33 +1750,36 @@ class PrioritizerTest : public ::testing
     ASSERT_EQ(0, r);
     ASSERT_LE(pref1, pref2);
   }
 
  private:
   nr_interface_prioritizer *prioritizer_;
 };
 
-class PacketFilterTest : public ::testing::Test {
+class PacketFilterTest : public StunTest {
  public:
   PacketFilterTest(): filter_(nullptr) {}
 
   void SetUp() {
+    StunTest::SetUp();
+
     // Set up enough of the ICE ctx to allow the packet filter to work
     ice_ctx_ = NrIceCtx::Create("test", true);
 
     nsCOMPtr<nsIUDPSocketFilterHandler> handler =
       do_GetService(NS_STUN_UDP_SOCKET_FILTER_HANDLER_CONTRACTID);
     handler->NewFilter(getter_AddRefs(filter_));
   }
 
   void TearDown() {
-    test_utils->sts_target()->Dispatch(WrapRunnable(this,
+    test_utils_->sts_target()->Dispatch(WrapRunnable(this,
                                                     &PacketFilterTest::TearDown_s),
                                        NS_DISPATCH_SYNC);
+    StunTest::TearDown();
   }
 
   void TearDown_s() {
     ice_ctx_ = nullptr;
   }
 
   void TestIncoming(const uint8_t* data, uint32_t len,
                     uint8_t from_addr, int from_port,
@@ -1723,165 +1816,165 @@ class PacketFilterTest : public ::testin
   }
 
   nsCOMPtr<nsIUDPSocketFilter> filter_;
   RefPtr<NrIceCtx> ice_ctx_;
 };
 }  // end namespace
 
 TEST_F(IceGatherTest, TestGatherFakeStunServerHostnameNoResolver) {
-  if (g_stun_server_hostname.empty()) {
+  if (stun_server_hostname_.empty()) {
     return;
   }
 
   EnsurePeer();
-  peer_->SetStunServer(g_stun_server_hostname, kDefaultStunServerPort);
+  peer_->SetStunServer(stun_server_hostname_, kDefaultStunServerPort);
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherFakeStunServerTcpHostnameNoResolver) {
-  if (g_stun_server_hostname.empty()) {
+  if (stun_server_hostname_.empty()) {
     return;
   }
 
   EnsurePeer(ICE_TEST_PEER_OFFERER | ICE_TEST_PEER_ENABLED_TCP);
-  peer_->SetStunServer(g_stun_server_hostname, kDefaultStunServerPort,
+  peer_->SetStunServer(stun_server_hostname_, kDefaultStunServerPort,
     kNrIceTransportTcp);
   Gather();
   ASSERT_TRUE(StreamHasMatchingCandidate(0, " TCP "));
 }
 
 TEST_F(IceGatherTest, TestGatherFakeStunServerIpAddress) {
-  if (g_stun_server_address.empty()) {
+  if (stun_server_address_.empty()) {
     return;
   }
 
   EnsurePeer();
-  peer_->SetStunServer(g_stun_server_address, kDefaultStunServerPort);
-  peer_->SetFakeResolver();
+  peer_->SetStunServer(stun_server_address_, kDefaultStunServerPort);
+  peer_->SetFakeResolver(stun_server_address_, stun_server_hostname_);
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherStunServerIpAddressDefaultRouteOnly) {
-  if (g_stun_server_address.empty()) {
+  if (stun_server_address_.empty()) {
     return;
   }
 
-  peer_ = new IceTestPeer("P1", true, false, false, false, true);
+  peer_ = new IceTestPeer("P1", test_utils_, true, false, false, false, true);
   peer_->AddStream(1);
-  peer_->SetStunServer(g_stun_server_address, kDefaultStunServerPort);
-  peer_->SetFakeResolver();
+  peer_->SetStunServer(stun_server_address_, kDefaultStunServerPort);
+  peer_->SetFakeResolver(stun_server_address_, stun_server_hostname_);
   Gather();
   ASSERT_FALSE(StreamHasMatchingCandidate(0, " host "));
 }
 
 TEST_F(IceGatherTest, TestGatherFakeStunServerHostname) {
-  if (g_stun_server_hostname.empty()) {
+  if (stun_server_hostname_.empty()) {
     return;
   }
 
   EnsurePeer();
-  peer_->SetStunServer(g_stun_server_hostname, kDefaultStunServerPort);
-  peer_->SetFakeResolver();
+  peer_->SetStunServer(stun_server_hostname_, kDefaultStunServerPort);
+  peer_->SetFakeResolver(stun_server_address_, stun_server_hostname_);
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherFakeStunBogusHostname) {
   EnsurePeer();
   peer_->SetStunServer(kBogusStunServerHostname, kDefaultStunServerPort);
-  peer_->SetFakeResolver();
+  peer_->SetFakeResolver(stun_server_address_, stun_server_hostname_);
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherDNSStunServerIpAddress) {
-  if (g_stun_server_address.empty()) {
+  if (stun_server_address_.empty()) {
     return;
   }
 
   EnsurePeer();
-  peer_->SetStunServer(g_stun_server_address, kDefaultStunServerPort);
+  peer_->SetStunServer(stun_server_address_, kDefaultStunServerPort);
   peer_->SetDNSResolver();
   Gather();
   ASSERT_TRUE(StreamHasMatchingCandidate(0, " UDP "));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "typ srflx raddr"));
 }
 
 TEST_F(IceGatherTest, TestGatherDNSStunServerIpAddressTcp) {
-  if (g_stun_server_address.empty()) {
+  if (stun_server_address_.empty()) {
     return;
   }
 
   EnsurePeer(ICE_TEST_PEER_OFFERER | ICE_TEST_PEER_ENABLED_TCP);
-  peer_->SetStunServer(g_stun_server_address, kDefaultStunServerPort,
+  peer_->SetStunServer(stun_server_address_, kDefaultStunServerPort,
     kNrIceTransportTcp);
   peer_->SetDNSResolver();
   Gather();
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "tcptype passive"));
   ASSERT_FALSE(StreamHasMatchingCandidate(0, "tcptype passive", " 9 "));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "tcptype so"));
   ASSERT_FALSE(StreamHasMatchingCandidate(0, "tcptype so", " 9 "));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "tcptype active", " 9 "));
 }
 
 TEST_F(IceGatherTest, TestGatherDNSStunServerHostname) {
-  if (g_stun_server_hostname.empty()) {
+  if (stun_server_hostname_.empty()) {
     return;
   }
 
   EnsurePeer();
-  peer_->SetStunServer(g_stun_server_hostname, kDefaultStunServerPort);
+  peer_->SetStunServer(stun_server_hostname_, kDefaultStunServerPort);
   peer_->SetDNSResolver();
   Gather();
   ASSERT_TRUE(StreamHasMatchingCandidate(0, " UDP "));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "typ srflx raddr"));
 }
 
 TEST_F(IceGatherTest, TestGatherDNSStunServerHostnameTcp) {
   EnsurePeer(ICE_TEST_PEER_OFFERER | ICE_TEST_PEER_ENABLED_TCP);
-  peer_->SetStunServer(g_stun_server_hostname, kDefaultStunServerPort,
+  peer_->SetStunServer(stun_server_hostname_, kDefaultStunServerPort,
     kNrIceTransportTcp);
   peer_->SetDNSResolver();
   Gather();
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "tcptype passive"));
   ASSERT_FALSE(StreamHasMatchingCandidate(0, "tcptype passive", " 9 "));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "tcptype so"));
   ASSERT_FALSE(StreamHasMatchingCandidate(0, "tcptype so", " 9 "));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "tcptype active", " 9 "));
 }
 
 TEST_F(IceGatherTest, TestGatherDNSStunServerHostnameBothUdpTcp) {
-  if (g_stun_server_hostname.empty()) {
+  if (stun_server_hostname_.empty()) {
     return;
   }
 
   std::vector<NrIceStunServer> stun_servers;
 
   EnsurePeer(ICE_TEST_PEER_OFFERER | ICE_TEST_PEER_ENABLED_TCP);
-  stun_servers.push_back(*NrIceStunServer::Create(g_stun_server_hostname,
+  stun_servers.push_back(*NrIceStunServer::Create(stun_server_hostname_,
     kDefaultStunServerPort, kNrIceTransportUdp));
-  stun_servers.push_back(*NrIceStunServer::Create(g_stun_server_hostname,
+  stun_servers.push_back(*NrIceStunServer::Create(stun_server_hostname_,
     kDefaultStunServerPort, kNrIceTransportTcp));
   peer_->SetStunServers(stun_servers);
   peer_->SetDNSResolver();
   Gather();
   ASSERT_TRUE(StreamHasMatchingCandidate(0, " UDP "));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, " TCP "));
 }
 
 TEST_F(IceGatherTest, TestGatherDNSStunServerIpAddressBothUdpTcp) {
-  if (g_stun_server_address.empty()) {
+  if (stun_server_address_.empty()) {
     return;
   }
 
   std::vector<NrIceStunServer> stun_servers;
 
   EnsurePeer(ICE_TEST_PEER_OFFERER | ICE_TEST_PEER_ENABLED_TCP);
-  stun_servers.push_back(*NrIceStunServer::Create(g_stun_server_address,
+  stun_servers.push_back(*NrIceStunServer::Create(stun_server_address_,
     kDefaultStunServerPort, kNrIceTransportUdp));
-  stun_servers.push_back(*NrIceStunServer::Create(g_stun_server_address,
+  stun_servers.push_back(*NrIceStunServer::Create(stun_server_address_,
     kDefaultStunServerPort, kNrIceTransportTcp));
   peer_->SetStunServers(stun_servers);
   peer_->SetDNSResolver();
   Gather();
   ASSERT_TRUE(StreamHasMatchingCandidate(0, " UDP "));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, " TCP "));
 }
 
@@ -1899,47 +1992,47 @@ TEST_F(IceGatherTest, TestGatherDNSStunB
     kNrIceTransportTcp);
   peer_->SetDNSResolver();
   Gather();
   ASSERT_TRUE(StreamHasMatchingCandidate(0, " TCP "));
 }
 
 TEST_F(IceGatherTest, TestDefaultCandidate) {
   EnsurePeer();
-  peer_->SetStunServer(g_stun_server_hostname, kDefaultStunServerPort);
+  peer_->SetStunServer(stun_server_hostname_, kDefaultStunServerPort);
   Gather();
   NrIceCandidate default_candidate;
   ASSERT_TRUE(NS_SUCCEEDED(peer_->GetDefaultCandidate(0, &default_candidate)));
 }
 
 TEST_F(IceGatherTest, TestGatherTurn) {
   EnsurePeer();
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
-  peer_->SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                       g_turn_user, g_turn_password, kNrIceTransportUdp);
+  peer_->SetTurnServer(turn_server_, kDefaultStunServerPort,
+                       turn_user_, turn_password_, kNrIceTransportUdp);
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherTurnTcp) {
   EnsurePeer();
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
-  peer_->SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                       g_turn_user, g_turn_password, kNrIceTransportTcp);
+  peer_->SetTurnServer(turn_server_, kDefaultStunServerPort,
+                       turn_user_, turn_password_, kNrIceTransportTcp);
   Gather();
 }
 
 TEST_F(IceGatherTest, TestGatherDisableComponent) {
-  if (g_stun_server_hostname.empty()) {
+  if (stun_server_hostname_.empty()) {
     return;
   }
 
   EnsurePeer();
-  peer_->SetStunServer(g_stun_server_hostname, kDefaultStunServerPort);
+  peer_->SetStunServer(stun_server_hostname_, kDefaultStunServerPort);
   peer_->AddStream(2);
   peer_->DisableComponent(1, 2);
   Gather();
   std::vector<std::string> candidates =
     peer_->GetCandidates(1);
 
   for (size_t i=0; i<candidates.size(); ++i) {
     size_t sp1 = candidates[i].find(' ');
@@ -1949,25 +2042,25 @@ TEST_F(IceGatherTest, TestGatherDisableC
 
 TEST_F(IceGatherTest, TestGatherVerifyNoLoopback) {
   Gather();
   ASSERT_FALSE(StreamHasMatchingCandidate(0, "127.0.0.1"));
 }
 
 TEST_F(IceGatherTest, TestGatherAllowLoopback) {
   // Set up peer with loopback allowed.
-  peer_ = new IceTestPeer("P1", true, true);
+  peer_ = new IceTestPeer("P1", test_utils_, true, true);
   peer_->AddStream(1);
   Gather();
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "127.0.0.1"));
 }
 
 TEST_F(IceGatherTest, TestGatherTcpDisabled) {
   // Set up peer with tcp disabled.
-  peer_ = new IceTestPeer("P1", true, false, false);
+  peer_ = new IceTestPeer("P1", test_utils_, true, false, false);
   peer_->AddStream(1);
   Gather();
   ASSERT_FALSE(StreamHasMatchingCandidate(0, " TCP "));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, " UDP "));
 }
 
 // Verify that a bogus candidate doesn't cause crashes on the
 // main thread. See bug 856433.
@@ -2060,17 +2153,17 @@ TEST_F(IceGatherTest, TestStunServerTric
   ASSERT_FALSE(StreamHasMatchingCandidate(0, "192.0.2.1"));
   WaitForGather();
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "192.0.2.1"));
 }
 
 // Test default route only with our fake STUN server and
 // apparently NATted.
 TEST_F(IceGatherTest, TestFakeStunServerNatedDefaultRouteOnly) {
-  peer_ = new IceTestPeer("P1", true, false, false, false, true);
+  peer_ = new IceTestPeer("P1", test_utils_, true, false, false, false, true);
   peer_->AddStream(1);
   UseFakeStunUdpServerWithResponse("192.0.2.1", 3333);
   Gather(0);
   WaitForGather();
   DumpCandidates(0);
   ASSERT_FALSE(StreamHasMatchingCandidate(0, "host"));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "srflx"));
   NrIceCandidate default_candidate;
@@ -2078,17 +2171,17 @@ TEST_F(IceGatherTest, TestFakeStunServer
   if (NS_SUCCEEDED(rv)) {
     ASSERT_NE(NrIceCandidate::ICE_HOST, default_candidate.type);
   }
 }
 
 // Test default route only with our fake STUN server and
 // apparently non-NATted.
 TEST_F(IceGatherTest, TestFakeStunServerNoNatDefaultRouteOnly) {
-  peer_ = new IceTestPeer("P1", true, false, false, false, true);
+  peer_ = new IceTestPeer("P1", test_utils_, true, false, false, false, true);
   peer_->AddStream(1);
   UseTestStunServer();
   Gather(0);
   WaitForGather();
   DumpCandidates(0);
   ASSERT_FALSE(StreamHasMatchingCandidate(0, "host"));
   ASSERT_TRUE(StreamHasMatchingCandidate(0, "srflx"));
 }
@@ -2341,70 +2434,70 @@ TEST_F(IceConnectTest, TestGatherSymmetr
   AddStream("first", 1);
   UseNat();
   SetFilteringType(TestNat::PORT_DEPENDENT);
   SetMappingType(TestNat::PORT_DEPENDENT);
   ASSERT_TRUE(Gather());
 }
 
 TEST_F(IceConnectTest, TestConnectSymmetricNat) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
   UseNat();
   SetFilteringType(TestNat::PORT_DEPENDENT);
   SetMappingType(TestNat::PORT_DEPENDENT);
   p1_->SetExpectedTypes(NrIceCandidate::Type::ICE_RELAYED,
                         NrIceCandidate::Type::ICE_RELAYED);
   p2_->SetExpectedTypes(NrIceCandidate::Type::ICE_RELAYED,
                         NrIceCandidate::Type::ICE_RELAYED);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_);
   ASSERT_TRUE(Gather());
   Connect();
 }
 
 TEST_F(IceConnectTest, TestGatherNatBlocksUDP) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
   UseNat();
   BlockUdp();
   std::vector<NrIceTurnServer> turn_servers;
-  std::vector<unsigned char> password_vec(g_turn_password.begin(),
-                                          g_turn_password.end());
+  std::vector<unsigned char> password_vec(turn_password_.begin(),
+                                          turn_password_.end());
   turn_servers.push_back(
-      *NrIceTurnServer::Create(g_turn_server, kDefaultStunServerPort,
-                               g_turn_user, password_vec, kNrIceTransportTcp));
+      *NrIceTurnServer::Create(turn_server_, kDefaultStunServerPort,
+                               turn_user_, password_vec, kNrIceTransportTcp));
   turn_servers.push_back(
-      *NrIceTurnServer::Create(g_turn_server, kDefaultStunServerPort,
-                               g_turn_user, password_vec, kNrIceTransportUdp));
+      *NrIceTurnServer::Create(turn_server_, kDefaultStunServerPort,
+                               turn_user_, password_vec, kNrIceTransportUdp));
   SetTurnServers(turn_servers);
   // We have to wait for the UDP-based stuff to time out.
   ASSERT_TRUE(Gather(kDefaultTimeout * 3));
 }
 
 TEST_F(IceConnectTest, TestConnectNatBlocksUDP) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
   UseNat();
   BlockUdp();
   std::vector<NrIceTurnServer> turn_servers;
-  std::vector<unsigned char> password_vec(g_turn_password.begin(),
-                                          g_turn_password.end());
+  std::vector<unsigned char> password_vec(turn_password_.begin(),
+                                          turn_password_.end());
   turn_servers.push_back(
-      *NrIceTurnServer::Create(g_turn_server, kDefaultStunServerPort,
-                               g_turn_user, password_vec, kNrIceTransportTcp));
+      *NrIceTurnServer::Create(turn_server_, kDefaultStunServerPort,
+                               turn_user_, password_vec, kNrIceTransportTcp));
   turn_servers.push_back(
-      *NrIceTurnServer::Create(g_turn_server, kDefaultStunServerPort,
-                               g_turn_user, password_vec, kNrIceTransportUdp));
+      *NrIceTurnServer::Create(turn_server_, kDefaultStunServerPort,
+                               turn_user_, password_vec, kNrIceTransportUdp));
   SetTurnServers(turn_servers);
   p1_->SetExpectedTypes(NrIceCandidate::Type::ICE_RELAYED,
                         NrIceCandidate::Type::ICE_RELAYED,
                         kNrIceTransportTcp);
   p2_->SetExpectedTypes(NrIceCandidate::Type::ICE_RELAYED,
                         NrIceCandidate::Type::ICE_RELAYED,
                         kNrIceTransportTcp);
   ASSERT_TRUE(Gather(kDefaultTimeout * 3));
@@ -2512,36 +2605,41 @@ void DelayRelayCandidates(
     } else {
       (*i)->Schedule(0);
     }
   }
 }
 
 void AddNonPairableCandidates(
     std::vector<SchedulableTrickleCandidate*>& candidates,
-    IceTestPeer *peer, size_t stream, int net_type) {
+    IceTestPeer *peer, size_t stream, int net_type,
+    MtransportTestUtils* test_utils_) {
   for (int i=1; i<5; i++) {
     if (net_type == i)
       continue;
     switch (i) {
       case 1:
         candidates.push_back(new SchedulableTrickleCandidate(peer, stream,
-                   "candidate:0 1 UDP 2113601790 10.0.0.1 12345 typ host"));
+                   "candidate:0 1 UDP 2113601790 10.0.0.1 12345 typ host",
+                   test_utils_));
         break;
       case 2:
         candidates.push_back(new SchedulableTrickleCandidate(peer, stream,
-                   "candidate:0 1 UDP 2113601791 172.16.1.1 12345 typ host"));
+                   "candidate:0 1 UDP 2113601791 172.16.1.1 12345 typ host",
+                   test_utils_));
         break;
       case 3:
         candidates.push_back(new SchedulableTrickleCandidate(peer, stream,
-                   "candidate:0 1 UDP 2113601792 192.168.0.1 12345 typ host"));
+                   "candidate:0 1 UDP 2113601792 192.168.0.1 12345 typ host",
+                   test_utils_));
         break;
       case 4:
         candidates.push_back(new SchedulableTrickleCandidate(peer, stream,
-                   "candidate:0 1 UDP 2113601793 100.64.1.1 12345 typ host"));
+                   "candidate:0 1 UDP 2113601793 100.64.1.1 12345 typ host",
+                   test_utils_));
         break;
       default:
         UNIMPLEMENTED;
     }
   }
 
   for (auto i = candidates.rbegin(); i != candidates.rend(); ++i) {
     std::cerr << "Scheduling candidate: " << (*i)->Candidate().c_str() << std::endl;
@@ -2721,180 +2819,180 @@ TEST_F(IceConnectTest, DISABLED_TestSend
   SetCandidateFilter(IsTcpSoCandidate);
   SetExpectedTypes(NrIceCandidate::Type::ICE_HOST,
     NrIceCandidate::Type::ICE_HOST, kNrIceTransportTcp);
   Connect();
   SendReceive();
 }
 
 TEST_F(IceConnectTest, TestConnectTurn) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_);
   ASSERT_TRUE(Gather());
   Connect();
 }
 
 TEST_F(IceConnectTest, TestConnectTurnWithDelay) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_);
   SetCandidateFilter(SabotageHostCandidateAndDropReflexive);
   p1_->Gather();
   PR_Sleep(500);
   p2_->Gather();
   ConnectTrickle(TRICKLE_REAL);
   WaitForGather();
   WaitForComplete();
 }
 
 TEST_F(IceConnectTest, TestConnectTurnWithNormalTrickleDelay) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_);
   ASSERT_TRUE(Gather());
   ConnectTrickle();
   RealisticTrickleDelay(p1_->ControlTrickle(0));
   RealisticTrickleDelay(p2_->ControlTrickle(0));
 
   ASSERT_TRUE_WAIT(p1_->ice_complete(), kDefaultTimeout);
   ASSERT_TRUE_WAIT(p2_->ice_complete(), kDefaultTimeout);
   AssertCheckingReached();
 }
 
 TEST_F(IceConnectTest, TestConnectTurnWithNormalTrickleDelayOneSided) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_);
   ASSERT_TRUE(Gather());
   ConnectTrickle();
   RealisticTrickleDelay(p1_->ControlTrickle(0));
   p2_->SimulateTrickle(0);
 
   ASSERT_TRUE_WAIT(p1_->ice_complete(), kDefaultTimeout);
   ASSERT_TRUE_WAIT(p2_->ice_complete(), kDefaultTimeout);
   AssertCheckingReached();
 }
 
 TEST_F(IceConnectTest, TestConnectTurnWithLargeTrickleDelay) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_);
   SetCandidateFilter(SabotageHostCandidateAndDropReflexive);
   ASSERT_TRUE(Gather());
   ConnectTrickle();
   // Trickle host candidates immediately, but delay relay candidates
   DelayRelayCandidates(p1_->ControlTrickle(0), 3700);
   DelayRelayCandidates(p2_->ControlTrickle(0), 3700);
 
   ASSERT_TRUE_WAIT(p1_->ice_complete(), kDefaultTimeout);
   ASSERT_TRUE_WAIT(p2_->ice_complete(), kDefaultTimeout);
   AssertCheckingReached();
 }
 
 TEST_F(IceConnectTest, TestConnectTurnTcp) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password, kNrIceTransportTcp);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_, kNrIceTransportTcp);
   ASSERT_TRUE(Gather());
   Connect();
 }
 
 TEST_F(IceConnectTest, TestConnectTurnOnly) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_);
   ASSERT_TRUE(Gather());
   SetCandidateFilter(IsRelayCandidate);
   SetExpectedTypes(NrIceCandidate::Type::ICE_RELAYED,
                    NrIceCandidate::Type::ICE_RELAYED);
   Connect();
 }
 
 TEST_F(IceConnectTest, TestConnectTurnTcpOnly) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password, kNrIceTransportTcp);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_, kNrIceTransportTcp);
   ASSERT_TRUE(Gather());
   SetCandidateFilter(IsRelayCandidate);
   SetExpectedTypes(NrIceCandidate::Type::ICE_RELAYED,
                    NrIceCandidate::Type::ICE_RELAYED,
                    kNrIceTransportTcp);
   Connect();
 }
 
 TEST_F(IceConnectTest, TestSendReceiveTurnOnly) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_);
   ASSERT_TRUE(Gather());
   SetCandidateFilter(IsRelayCandidate);
   SetExpectedTypes(NrIceCandidate::Type::ICE_RELAYED,
                    NrIceCandidate::Type::ICE_RELAYED);
   Connect();
   SendReceive();
 }
 
 TEST_F(IceConnectTest, TestSendReceiveTurnTcpOnly) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
-  SetTurnServer(g_turn_server, kDefaultStunServerPort,
-                g_turn_user, g_turn_password, kNrIceTransportTcp);
+  SetTurnServer(turn_server_, kDefaultStunServerPort,
+                turn_user_, turn_password_, kNrIceTransportTcp);
   ASSERT_TRUE(Gather());
   SetCandidateFilter(IsRelayCandidate);
   SetExpectedTypes(NrIceCandidate::Type::ICE_RELAYED,
                    NrIceCandidate::Type::ICE_RELAYED,
                    kNrIceTransportTcp);
   Connect();
   SendReceive();
 }
 
 TEST_F(IceConnectTest, TestSendReceiveTurnBothOnly) {
-  if (g_turn_server.empty())
+  if (turn_server_.empty())
     return;
 
   AddStream("first", 1);
   std::vector<NrIceTurnServer> turn_servers;
-  std::vector<unsigned char> password_vec(g_turn_password.begin(),
-                                          g_turn_password.end());
+  std::vector<unsigned char> password_vec(turn_password_.begin(),
+                                          turn_password_.end());
   turn_servers.push_back(*NrIceTurnServer::Create(
-                           g_turn_server, kDefaultStunServerPort,
-                           g_turn_user, password_vec, kNrIceTransportTcp));
+                           turn_server_, kDefaultStunServerPort,
+                           turn_user_, password_vec, kNrIceTransportTcp));
   turn_servers.push_back(*NrIceTurnServer::Create(
-                           g_turn_server, kDefaultStunServerPort,
-                           g_turn_user, password_vec, kNrIceTransportUdp));
+                           turn_server_, kDefaultStunServerPort,
+                           turn_user_, password_vec, kNrIceTransportUdp));
   SetTurnServers(turn_servers);
   ASSERT_TRUE(Gather());
   SetCandidateFilter(IsRelayCandidate);
   // UDP is preferred.
   SetExpectedTypes(NrIceCandidate::Type::ICE_RELAYED,
                    NrIceCandidate::Type::ICE_RELAYED,
                    kNrIceTransportUdp);
   Connect();
@@ -2952,34 +3050,36 @@ TEST_F(IceConnectTest, TestHostCandPairi
 
   int host_net = p1_->GetCandidatesPrivateIpv4Range(0);
   if (host_net <= 0) {
     // TODO bug 1226838: make this work with multiple private IPs
     FAIL() << "This test needs exactly one private IPv4 host candidate to work" << std::endl;
   }
 
   ConnectTrickle();
-  AddNonPairableCandidates(p1_->ControlTrickle(0), p1_, 0, host_net);
-  AddNonPairableCandidates(p2_->ControlTrickle(0), p2_, 0, host_net);
+  AddNonPairableCandidates(p1_->ControlTrickle(0), p1_, 0, host_net,
+                           test_utils_);
+  AddNonPairableCandidates(p2_->ControlTrickle(0), p2_, 0, host_net,
+                           test_utils_);
 
   std::vector<NrIceCandidatePair> pairs;
   p1_->GetCandidatePairs(0, &pairs);
   for (auto p : pairs) {
     std::cerr << "Verifying pair:" << std::endl;
     p1_->DumpCandidatePair(p);
     nr_transport_addr addr;
     nr_str_port_to_transport_addr(p.local.local_addr.host.c_str(), 0, IPPROTO_UDP, &addr);
     ASSERT_TRUE(nr_transport_addr_get_private_addr_range(&addr) == host_net);
     nr_str_port_to_transport_addr(p.remote.cand_addr.host.c_str(), 0, IPPROTO_UDP, &addr);
     ASSERT_TRUE(nr_transport_addr_get_private_addr_range(&addr) == host_net);
   }
 }
 
 TEST_F(IceConnectTest, TestSrflxCandPairingFilter) {
-  if (g_stun_server_address.empty()) {
+  if (stun_server_address_.empty()) {
     return;
   }
 
   AddStream("first", 1);
   ASSERT_TRUE(Gather(kDefaultTimeout));
   SetCandidateFilter(IsSrflxCandidate);
 
   if (p1_->GetCandidatesPrivateIpv4Range(0) <= 0) {
@@ -3228,146 +3328,8 @@ TEST(InternalsTest, TestAddBogusAttribut
   ASSERT_EQ(0, nr_stun_message_create(&req));
   Data *data;
   ASSERT_EQ(0, r_data_alloc(&data, 3000));
   memset(data->data, 'A', data->len);
   ASSERT_TRUE(nr_stun_message_add_message_integrity_attribute(req, data));
   ASSERT_EQ(0, r_data_destroy(&data));
   ASSERT_EQ(0, nr_stun_message_destroy(&req));
 }
-
-static std::string get_environment(const char *name) {
-  char *value = getenv(name);
-
-  if (!value)
-    return "";
-
-  return value;
-}
-
-// DNS resolution helper code
-static std::string
-Resolve(const std::string& fqdn, int address_family)
-{
-  struct addrinfo hints;
-  memset(&hints, 0, sizeof(hints));
-  hints.ai_family = address_family;
-  hints.ai_protocol = IPPROTO_UDP;
-  struct addrinfo *res;
-  int err = getaddrinfo(fqdn.c_str(), nullptr, &hints, &res);
-  if (err) {
-    std::cerr << "Error in getaddrinfo: " << err << std::endl;
-    return "";
-  }
-
-  char str_addr[64] = {0};
-  switch (res->ai_family) {
-    case AF_INET:
-      inet_ntop(
-          AF_INET,
-          &reinterpret_cast<struct sockaddr_in*>(res->ai_addr)->sin_addr,
-          str_addr,
-          sizeof(str_addr));
-      break;
-    case AF_INET6:
-      inet_ntop(
-          AF_INET6,
-          &reinterpret_cast<struct sockaddr_in6*>(res->ai_addr)->sin6_addr,
-          str_addr,
-          sizeof(str_addr));
-      break;
-    default:
-      std::cerr << "Got unexpected address family in DNS lookup: "
-                << res->ai_family << std::endl;
-      return "";
-  }
-
-  if (!strlen(str_addr)) {
-    std::cerr << "inet_ntop failed" << std::endl;
-  }
-
-  return str_addr;
-}
-
-int main(int argc, char **argv)
-{
-#ifdef ANDROID
-  // This test can cause intermittent oranges on the builders on Linux
-  CHECK_ENVIRONMENT_FLAG("MOZ_WEBRTC_TESTS")
-#endif
-
-  g_turn_server = get_environment("TURN_SERVER_ADDRESS");
-  g_turn_user = get_environment("TURN_SERVER_USER");
-  g_turn_password = get_environment("TURN_SERVER_PASSWORD");
-
-
-  if (g_turn_server.empty() ||
-      g_turn_user.empty(),
-      g_turn_password.empty()) {
-    printf(
-        "Set TURN_SERVER_ADDRESS, TURN_SERVER_USER, and TURN_SERVER_PASSWORD\n"
-        "environment variables to run this test\n");
-    g_turn_server="";
-  }
-
-  std::string tmp = get_environment("STUN_SERVER_ADDRESS");
-  if (tmp != "")
-    g_stun_server_address = tmp;
-
-
-  tmp = get_environment("STUN_SERVER_HOSTNAME");
-  if (tmp != "")
-    g_stun_server_hostname = tmp;
-
-  tmp = get_environment("MOZ_DISABLE_NONLOCAL_CONNECTIONS");
-
-  if ((tmp != "" && tmp != "0") || getenv("MOZ_UPLOAD_DIR")) {
-    // We're assuming that MOZ_UPLOAD_DIR is only set on tbpl;
-    // MOZ_DISABLE_NONLOCAL_CONNECTIONS probably should be set when running the
-    // cpp unit-tests, but is not presently.
-    g_stun_server_address = "";
-    g_stun_server_hostname = "";
-    g_turn_server = "";
-  }
-
-  test_utils = new MtransportTestUtils();
-  NSS_NoDB_Init(nullptr);
-  NSS_SetDomesticPolicy();
-
-  // If only a STUN server FQDN was provided, look up its IP address for the
-  // address-only tests.
-  if (g_stun_server_address.empty() && !g_stun_server_hostname.empty()) {
-    g_stun_server_address = Resolve(g_stun_server_hostname, AF_INET);
-  }
-
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  ::testing::TestEventListeners& listeners =
-        ::testing::UnitTest::GetInstance()->listeners();
-  // Adds a listener to the end.  Google Test takes the ownership.
-
-  listeners.Append(new test::RingbufferDumper(test_utils));
-  test_utils->sts_target()->Dispatch(
-      WrapRunnableNM(&TestStunServer::GetInstance, AF_INET),
-                     NS_DISPATCH_SYNC);
-  test_utils->sts_target()->Dispatch(
-    WrapRunnableNM(&TestStunServer::GetInstance, AF_INET6),
-                   NS_DISPATCH_SYNC);
-
-  test_utils->sts_target()->Dispatch(
-      WrapRunnableNM(&TestStunTcpServer::GetInstance, AF_INET),
-                     NS_DISPATCH_SYNC);
-  test_utils->sts_target()->Dispatch(
-    WrapRunnableNM(&TestStunTcpServer::GetInstance, AF_INET6),
-                   NS_DISPATCH_SYNC);
-
-  int rv = RUN_ALL_TESTS();
-
-  test_utils->sts_target()->Dispatch(
-    WrapRunnableNM(&TestStunServer::ShutdownInstance), NS_DISPATCH_SYNC);
-
-  test_utils->sts_target()->Dispatch(
-    WrapRunnableNM(&TestStunTcpServer::ShutdownInstance), NS_DISPATCH_SYNC);
-
-  delete test_utils;
-  return rv;
-}
--- a/media/mtransport/test/moz.build
+++ b/media/mtransport/test/moz.build
@@ -1,59 +1,55 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 if CONFIG['OS_TARGET'] != 'WINNT' and CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
-    CppUnitTests([
-        'buffered_stun_socket_unittest',
-        'ice_unittest',
-        'multi_tcp_socket_unittest',
-        'nrappkit_unittest',
-        'proxy_tunnel_socket_unittest',
-        'rlogringbuffer_unittest',
-        'runnable_utils_unittest',
-        'simpletokenbucket_unittest',
-        'sockettransportservice_unittest',
-        'test_nr_socket_unittest',
-        'TestSyncRunnable',
-        'transport_unittests',
-        'turn_unittest',
-    ])
+    SOURCES += [
+        'buffered_stun_socket_unittest.cpp',
+        'ice_unittest.cpp',
+        'multi_tcp_socket_unittest.cpp',
+        'nrappkit_unittest.cpp',
+        'proxy_tunnel_socket_unittest.cpp',
+        'rlogringbuffer_unittest.cpp',
+        'runnable_utils_unittest.cpp',
+        'simpletokenbucket_unittest.cpp',
+        'sockettransportservice_unittest.cpp',
+        'stunserver.cpp',
+        'test_nr_socket_unittest.cpp',
+        'TestSyncRunnable.cpp',
+        'transport_unittests.cpp',
+        'turn_unittest.cpp',
+    ]
 
     if CONFIG['MOZ_SCTP']:
-        CppUnitTests([
-            'sctp_unittest',
-        ])
+        SOURCES += [
+            'sctp_unittest.cpp',
+        ]
 
-for var in ('MOZILLA_INTERNAL_API', 'MOZILLA_XPCOMRT_API', 'MOZILLA_EXTERNAL_LINKAGE', 'HAVE_STRDUP', 'NR_SOCKET_IS_VOID_PTR', 'SCTP_DEBUG', 'INET'):
+
+for var in ('HAVE_STRDUP', 'NR_SOCKET_IS_VOID_PTR', 'SCTP_DEBUG', 'INET'):
     DEFINES[var] = True
 
 if CONFIG['OS_TARGET'] == 'Android':
     DEFINES['LINUX'] = True
     DEFINES['ANDROID'] = True
     LOCAL_INCLUDES += [
         '/media/mtransport/third_party/nrappkit/src/port/android/include',
     ]
 else:
     DEFINES['INET6'] = True
 
 if CONFIG['OS_TARGET'] == 'Linux':
     DEFINES['LINUX'] = True
     LOCAL_INCLUDES += [
         '/media/mtransport/third_party/nrappkit/src/port/linux/include',
     ]
-    USE_LIBS += [
-        'nspr',
-    ]
-    OS_LIBS += [
-        '-lrt',
-    ]
 
 if CONFIG['OS_TARGET'] == 'Darwin':
     LOCAL_INCLUDES += [
         '/media/mtransport/third_party/nrappkit/src/port/darwin/include',
     ]
 
 if CONFIG['OS_TARGET'] in ('DragonFly', 'FreeBSD', 'NetBSD', 'OpenBSD'):
     if CONFIG['OS_TARGET'] == 'Darwin':
@@ -89,40 +85,13 @@ LOCAL_INCLUDES += [
     '/media/mtransport/third_party/nrappkit/src/log',
     '/media/mtransport/third_party/nrappkit/src/plugin',
     '/media/mtransport/third_party/nrappkit/src/port/generic/include',
     '/media/mtransport/third_party/nrappkit/src/registry',
     '/media/mtransport/third_party/nrappkit/src/share',
     '/media/mtransport/third_party/nrappkit/src/stats',
     '/media/mtransport/third_party/nrappkit/src/util/',
     '/media/mtransport/third_party/nrappkit/src/util/libekr',
-    '/media/webrtc/trunk/testing/gtest/include/',
     '/netwerk/sctp/src/',
-    '/xpcom/libxpcomrt',
+    '/xpcom/tests/'
 ]
 
-USE_LIBS += [
-    '/media/webrtc/trunk/testing/gtest_gtest/gtest',
-    'fallible',
-    'mfbt',
-    'mozglue',
-    'mtransport_standalone',
-    'necko_standalone',
-    'nicer',
-    'nrappkit',
-    'nspr',
-    'nss',
-    'unicharutil_standalone',
-    'xpcomrt',
-]
-
-if not CONFIG['MOZ_NATIVE_NSS'] and not CONFIG['MOZ_FOLD_LIBS']:
-    USE_LIBS += [
-        # Statically linking NSS libssl ensures that we can debug NSS too
-        'static:/security/nss/lib/ssl/ssl',
-    ]
-
-if CONFIG['MOZ_SCTP']:
-    USE_LIBS += [
-        'nksctp_s',
-    ]
-
-USE_LIBS += ['mozglue']
+FINAL_LIBRARY = 'xul-gtest'
--- a/media/mtransport/test/mtransport_test_utils.h
+++ b/media/mtransport/test/mtransport_test_utils.h
@@ -4,105 +4,45 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 // Original author: ekr@rtfm.com
 
 #ifndef mtransport_test_utils_h__
 #define mtransport_test_utils_h__
 
-#include <iostream>
-
-#include "nspr.h"
 #include "nsCOMPtr.h"
 #include "nsNetCID.h"
-#include "nsXPCOMGlue.h"
-#include "nsXPCOM.h"
 
-#include "nsIComponentManager.h"
-#include "nsIComponentRegistrar.h"
 #include "nsIEventTarget.h"
-#include "nsIIOService.h"
-#include "nsIServiceManager.h"
-#include "nsISocketTransportService.h"
-#include "nsDirectoryServiceUtils.h"
-#include "nsDirectoryServiceDefs.h"
-#ifdef MOZ_CRASHREPORTER
-#include "nsICrashReporter.h"
-#endif
 #include "nsPISocketTransportService.h"
 #include "nsServiceManagerUtils.h"
-#if !defined(MOZILLA_XPCOMRT_API)
-#include "TestHarness.h"
-#else
-#include "XPCOMRTInit.h"
-class ScopedXPCOM {
-public:
-  explicit ScopedXPCOM(const char*)
-  {
-    NS_InitXPCOMRT();
-  }
-  ~ScopedXPCOM()
-  {
-    NS_ShutdownXPCOMRT();
-  }
-};
-#endif
 
 class MtransportTestUtils {
  public:
-  MtransportTestUtils() : xpcom_("") {
-    if (!sts_) {
+  MtransportTestUtils() {
       InitServices();
-    }
   }
 
   ~MtransportTestUtils() {
-    sts_->Shutdown();
   }
 
   void InitServices() {
     nsresult rv;
     sts_target_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
     MOZ_ASSERT(NS_SUCCEEDED(rv));
     sts_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
     MOZ_ASSERT(NS_SUCCEEDED(rv));
-
-#ifdef MOZ_CRASHREPORTER
-    char *crashreporter = PR_GetEnv("MOZ_CRASHREPORTER");
-    if (crashreporter && !strcmp(crashreporter, "1")) {
-      //TODO: move this to an even-more-common location to use in all
-      // C++ unittests
-      crashreporter_ = do_GetService("@mozilla.org/toolkit/crash-reporter;1");
-      if (crashreporter_) {
-        std::cerr << "Setting up crash reporting" << std::endl;
-
-        nsCOMPtr<nsIProperties> dirsvc =
-            do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
-        nsCOMPtr<nsIFile> cwd;
-        rv = dirsvc->Get(NS_OS_CURRENT_WORKING_DIR,
-                         NS_GET_IID(nsIFile),
-                         getter_AddRefs(cwd));
-        MOZ_ASSERT(NS_SUCCEEDED(rv));
-        crashreporter_->SetEnabled(true);
-        crashreporter_->SetMinidumpPath(cwd);
-      }
-    }
-#endif
   }
 
   nsCOMPtr<nsIEventTarget> sts_target() { return sts_target_; }
 
  private:
-  ScopedXPCOM xpcom_;
   nsCOMPtr<nsIEventTarget> sts_target_;
   nsCOMPtr<nsPISocketTransportService> sts_;
-#ifdef MOZ_CRASHREPORTER
-  nsCOMPtr<nsICrashReporter> crashreporter_;
-#endif
 };
 
 
 #define CHECK_ENVIRONMENT_FLAG(envname) \
   char *test_flag = getenv(envname); \
   if (!test_flag || strcmp(test_flag, "1")) { \
     printf("To run this test set %s=1 in your environment\n", envname); \
     exit(0); \
--- a/media/mtransport/test/multi_tcp_socket_unittest.cpp
+++ b/media/mtransport/test/multi_tcp_socket_unittest.cpp
@@ -16,51 +16,61 @@
 extern "C" {
 #include "nr_api.h"
 #include "nr_socket.h"
 #include "transport_addr.h"
 #include "ice_ctx.h"
 #include "nr_socket_multi_tcp.h"
 }
 
-#include "mtransport_test_utils.h"
-#include "gtest_ringbuffer_dumper.h"
-
 #include "nr_socket_prsock.h"
 
 #include "stunserver.h"
-// TODO(bcampen@mozilla.com): Big fat hack since the build system doesn't give
-// us a clean way to add object files to a single executable.
-#include "stunserver.cpp"
 
 #include "nricectx.h"
 #include "nricemediastream.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
 using namespace mozilla;
-MtransportTestUtils *test_utils;
 
 namespace {
 
-class MultiTcpSocketTest : public ::testing::Test {
+class MultiTcpSocketTest : public MtransportTest {
  public:
   MultiTcpSocketTest()
-    :socks(3,nullptr),
+    :MtransportTest(),
+     socks(3,nullptr),
      readable(false),
-     ice_ctx_(NrIceCtx::Create("stun", true))
+     ice_ctx_()
    {}
 
-  ~MultiTcpSocketTest() {
-    test_utils->sts_target()->Dispatch(
+  void SetUp() {
+    MtransportTest::SetUp();
+
+    ice_ctx_ = NrIceCtx::Create("stun", true);
+
+    test_utils_->sts_target()->Dispatch(
+        WrapRunnableNM(&TestStunTcpServer::GetInstance, AF_INET),
+                       NS_DISPATCH_SYNC);
+    test_utils_->sts_target()->Dispatch(
+      WrapRunnableNM(&TestStunTcpServer::GetInstance, AF_INET6),
+                     NS_DISPATCH_SYNC);
+  }
+
+
+  void TearDown() {
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::Shutdown_s),
             NS_DISPATCH_SYNC);
+
+    MtransportTest::TearDown();
   }
 
   DISALLOW_COPY_ASSIGN(MultiTcpSocketTest);
 
   static void SockReadable(NR_SOCKET s, int how, void *arg) {
     MultiTcpSocketTest *obj=static_cast<MultiTcpSocketTest *>(arg);
     obj->SetReadable(true);
   }
@@ -119,17 +129,17 @@ class MultiTcpSocketTest : public ::test
         &MultiTcpSocketTest::SockReadable, this);
     ASSERT_EQ(0, r);
   }
 
   nr_socket *Create(nr_socket_tcp_type tcp_type,
                     std::string stun_server_addr = "",
                     uint16_t stun_server_port = 0) {
     nr_socket *sock=nullptr;
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::Create_s, tcp_type,
                 stun_server_addr, stun_server_port, &sock),
             NS_DISPATCH_SYNC);
     return sock;
   }
 
   void Listen_s(nr_socket *sock) {
@@ -137,29 +147,29 @@ class MultiTcpSocketTest : public ::test
     int r=nr_socket_getaddr(sock, &addr);
     ASSERT_EQ(0, r);
     printf("Listening on %s\n", addr.as_string);
     r = nr_socket_listen(sock, 5);
     ASSERT_EQ(0, r);
   }
 
   void Listen(nr_socket *sock) {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::Listen_s, sock),
             NS_DISPATCH_SYNC);
   }
 
   void Destroy_s(nr_socket *sock) {
     int r = nr_socket_destroy(&sock);
     ASSERT_EQ(0, r);
   }
 
   void Destroy(nr_socket *sock) {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::Destroy_s, sock),
             NS_DISPATCH_SYNC);
   }
 
   void Connect_s(nr_socket *from, nr_socket *to) {
     nr_transport_addr addr_to;
     nr_transport_addr addr_from;
@@ -168,17 +178,17 @@ class MultiTcpSocketTest : public ::test
     r=nr_socket_getaddr(from, &addr_from);
     ASSERT_EQ(0, r);
     printf("Connecting from %s to %s\n", addr_from.as_string, addr_to.as_string);
     r=nr_socket_connect(from, &addr_to);
     ASSERT_EQ(0, r);
   }
 
   void Connect(nr_socket *from, nr_socket *to) {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::Connect_s, from, to),
             NS_DISPATCH_SYNC);
   }
 
   void ConnectSo_s(nr_socket *so1, nr_socket *so2) {
     nr_transport_addr addr_so1;
     nr_transport_addr addr_so2;
@@ -189,17 +199,17 @@ class MultiTcpSocketTest : public ::test
     printf("Connecting SO %s <-> %s\n", addr_so1.as_string, addr_so2.as_string);
     r=nr_socket_connect(so1, &addr_so2);
     ASSERT_EQ(0, r);
     r=nr_socket_connect(so2, &addr_so1);
     ASSERT_EQ(0, r);
   }
 
   void ConnectSo(nr_socket *from, nr_socket *to) {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::ConnectSo_s, from, to),
             NS_DISPATCH_SYNC);
   }
 
   void SendDataToAddress_s(nr_socket *from, nr_transport_addr *to, const char *data,
                            size_t len) {
     nr_transport_addr addr_from;
@@ -208,34 +218,34 @@ class MultiTcpSocketTest : public ::test
     ASSERT_EQ(0, r);
     printf("Sending %lu bytes %s -> %s\n", (unsigned long)len,
       addr_from.as_string, to->as_string);
     r=nr_socket_sendto(from, data, len, 0, to);
     ASSERT_EQ(0, r);
   }
 
   void SendData(nr_socket *from, nr_transport_addr *to, const char *data, size_t len) {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::SendDataToAddress_s, from, to, data,
                 len),
             NS_DISPATCH_SYNC);
   }
 
   void SendDataToSocket_s(nr_socket *from, nr_socket *to, const char *data,
                   size_t len) {
     nr_transport_addr addr_to;
 
     int r=nr_socket_getaddr(to, &addr_to);
     ASSERT_EQ(0, r);
     SendDataToAddress_s(from, &addr_to, data, len);
   }
 
   void SendData(nr_socket *from, nr_socket *to, const char *data, size_t len) {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::SendDataToSocket_s, from, to, data,
                 len),
             NS_DISPATCH_SYNC);
   }
 
   void RecvDataFromAddress_s(nr_transport_addr *expected_from,
                              nr_socket *sent_to,
@@ -266,17 +276,17 @@ class MultiTcpSocketTest : public ::test
       r=memcmp(expected_data, received_data, retlen);
       ASSERT_EQ(0, r);
     }
   }
 
   void RecvData(nr_transport_addr *expected_from, nr_socket *sent_to,
                 const char *expected_data = nullptr, size_t expected_len = 0) {
     ASSERT_TRUE_WAIT(IsReadable(), 1000);
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::RecvDataFromAddress_s,
                 expected_from, sent_to, expected_data,
                 expected_len),
             NS_DISPATCH_SYNC);
   }
 
   void RecvDataFromSocket_s(nr_socket *expected_from, nr_socket *sent_to,
@@ -287,17 +297,17 @@ class MultiTcpSocketTest : public ::test
     ASSERT_EQ(0, r);
 
     RecvDataFromAddress_s(&addr_from, sent_to, expected_data, expected_len);
   }
 
   void RecvData(nr_socket *expected_from, nr_socket *sent_to,
                 const char *expected_data, size_t expected_len) {
     ASSERT_TRUE_WAIT(IsReadable(), 1000);
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::RecvDataFromSocket_s,
                 expected_from, sent_to, expected_data, expected_len),
             NS_DISPATCH_SYNC);
   }
 
   void RecvDataFailed_s(nr_socket *sent_to, size_t expected_len, int expected_err) {
     SetReadable(false);
@@ -312,17 +322,17 @@ class MultiTcpSocketTest : public ::test
                          &retlen, 0, &retaddr);
     ASSERT_EQ(expected_err, r) << "Expecting receive failure " << expected_err
     << " on " << addr_to.as_string;
   }
 
   void RecvDataFailed(nr_socket *sent_to, size_t expected_len,
                       int expected_err) {
     ASSERT_TRUE_WAIT(IsReadable(), 1000);
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
             WrapRunnable(
                 this, &MultiTcpSocketTest::RecvDataFailed_s, sent_to, expected_len,
                 expected_err),
             NS_DISPATCH_SYNC);
   }
 
   void TransferData(nr_socket *from, nr_socket *to, const char *data,
                     size_t len) {
@@ -524,38 +534,8 @@ TEST_F(MultiTcpSocketTest, TestBigData) 
   TransferData(socks[0], socks[1], buf1, sizeof(buf1));
   TransferData(socks[0], socks[1], buf2, sizeof(buf2));
 // opposite dir
   SendData(socks[1], socks[0], buf2, sizeof(buf2));
   SendData(socks[1], socks[0], buf1, sizeof(buf1));
   RecvData(socks[1], socks[0], buf2, sizeof(buf2));
   RecvData(socks[1], socks[0], buf1, sizeof(buf1));
 }
-
-
-int main(int argc, char **argv)
-{
-  test_utils = new MtransportTestUtils();
-  NSS_NoDB_Init(nullptr); // For random number generation
-
-  ::testing::TestEventListeners& listeners =
-        ::testing::UnitTest::GetInstance()->listeners();
-  // Adds a listener to the end.  Google Test takes the ownership.
-  listeners.Append(new test::RingbufferDumper(test_utils));
-
-  test_utils->sts_target()->Dispatch(
-      WrapRunnableNM(&TestStunTcpServer::GetInstance, AF_INET),
-                     NS_DISPATCH_SYNC);
-  test_utils->sts_target()->Dispatch(
-    WrapRunnableNM(&TestStunTcpServer::GetInstance, AF_INET6),
-                   NS_DISPATCH_SYNC);
-
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-
-  test_utils->sts_target()->Dispatch(
-    WrapRunnableNM(&TestStunTcpServer::ShutdownInstance), NS_DISPATCH_SYNC);
-
-  delete test_utils;
-  return rv;
-}
--- a/media/mtransport/test/nrappkit_unittest.cpp
+++ b/media/mtransport/test/nrappkit_unittest.cpp
@@ -12,47 +12,45 @@
 #include "nsXPCOM.h"
 
 // nrappkit includes
 extern "C" {
 #include "nr_api.h"
 #include "async_timer.h"
 }
 
-#include "mtransport_test_utils.h"
 #include "runnable_utils.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
 using namespace mozilla;
 
-MtransportTestUtils *test_utils;
-
 namespace {
 
-class TimerTest : public ::testing::Test {
+class TimerTest : public MtransportTest {
  public:
-  TimerTest() : handle_(nullptr), fired_(false) {}
+  TimerTest() : MtransportTest(), handle_(nullptr), fired_(false) {}
+  virtual ~TimerTest() {}
 
   int ArmTimer(int timeout) {
     int ret;
 
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&ret, this, &TimerTest::ArmTimer_w, timeout),
         NS_DISPATCH_SYNC);
 
     return ret;
   }
 
   int ArmCancelTimer(int timeout) {
     int ret;
 
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&ret, this, &TimerTest::ArmCancelTimer_w, timeout),
         NS_DISPATCH_SYNC);
 
     return ret;
   }
 
   int ArmTimer_w(int timeout) {
     return NR_ASYNC_TIMER_SET(timeout, cb, this, &handle_);
@@ -65,31 +63,31 @@ class TimerTest : public ::testing::Test
       return r;
 
     return CancelTimer_w();
   }
 
   int CancelTimer() {
     int ret;
 
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&ret, this, &TimerTest::CancelTimer_w),
         NS_DISPATCH_SYNC);
 
     return ret;
   }
 
   int CancelTimer_w() {
     return NR_async_timer_cancel(handle_);
   }
 
   int Schedule() {
     int ret;
 
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&ret, this, &TimerTest::Schedule_w),
         NS_DISPATCH_SYNC);
 
     return ret;
   }
 
   int Schedule_w() {
     NR_ASYNC_SCHEDULE(cb, this);
@@ -129,19 +127,8 @@ TEST_F(TimerTest, CancelTimer0) {
   PR_Sleep(100);
   ASSERT_FALSE(fired_);
 }
 
 TEST_F(TimerTest, ScheduleTest) {
   Schedule();
   ASSERT_TRUE_WAIT(fired_, 1000);
 }
-
-int main(int argc, char **argv) {
-  test_utils = new MtransportTestUtils();
-
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-  delete test_utils;
-  return rv;
-}
--- a/media/mtransport/test/proxy_tunnel_socket_unittest.cpp
+++ b/media/mtransport/test/proxy_tunnel_socket_unittest.cpp
@@ -18,28 +18,26 @@ extern "C" {
 #include "nr_api.h"
 #include "nr_socket.h"
 #include "nr_proxy_tunnel.h"
 #include "transport_addr.h"
 #include "stun.h"
 }
 
 #include "databuffer.h"
-#include "mtransport_test_utils.h"
 #include "dummysocket.h"
 
 #include "nr_socket_prsock.h"
 #include "nriceresolverfake.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
 using namespace mozilla;
-MtransportTestUtils *test_utils;
 
 const std::string kRemoteAddr = "192.0.2.133";
 const uint16_t kRemotePort = 3333;
 
 const std::string kProxyHost = "example.com";
 const std::string kProxyAddr = "192.0.2.134";
 const uint16_t kProxyPort = 9999;
 
@@ -103,28 +101,30 @@ class DummyResolver {
     return resolver_;
   }
 
  private:
   nr_resolver_vtbl *vtbl_;
   nr_resolver *resolver_;
 };
 
-class ProxyTunnelSocketTest : public ::testing::Test {
+class ProxyTunnelSocketTest : public MtransportTest {
  public:
   ProxyTunnelSocketTest()
       : socket_impl_(nullptr),
         nr_socket_(nullptr) {}
 
   ~ProxyTunnelSocketTest() {
     nr_socket_destroy(&nr_socket_);
     nr_proxy_tunnel_config_destroy(&config_);
   }
 
-  void SetUp() {
+  void SetUp() override {
+    MtransportTest::SetUp();
+
     nr_resolver_ = resolver_impl_.get_nr_resolver();
 
     int r = nr_str_port_to_transport_addr(
         (char *)kRemoteAddr.c_str(), kRemotePort, IPPROTO_TCP, &remote_addr_);
     ASSERT_EQ(0, r);
 
     r = nr_str_port_to_transport_addr(
         (char *)kProxyAddr.c_str(), kProxyPort, IPPROTO_TCP, &proxy_addr_);
@@ -339,23 +339,8 @@ TEST_F(ProxyTunnelSocketTest, TestConnec
   socket_impl_->SetReadBuffer(reinterpret_cast<const uint8_t *>(kGarbageMessage.c_str()),
       kGarbageMessage.size());
 
   char buf[4096];
   size_t read = 0;
   r = nr_socket_read(nr_socket_, buf, sizeof(buf), &read, 0);
   ASSERT_EQ(0ul, read);
 }
-
-int main(int argc, char **argv)
-{
-  test_utils = new MtransportTestUtils();
-  NSS_NoDB_Init(nullptr);
-  NSS_SetDomesticPolicy();
-
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-
-  delete test_utils;
-  return rv;
-}
--- a/media/mtransport/test/rlogringbuffer_unittest.cpp
+++ b/media/mtransport/test/rlogringbuffer_unittest.cpp
@@ -30,16 +30,24 @@ class RLogRingBufferTest : public ::test
     RLogRingBufferTest() {
       Init();
     }
 
     ~RLogRingBufferTest() {
       Free();
     }
 
+    static void SetUpTestCase() {
+      NR_reg_init(NR_REG_MODE_LOCAL);
+      r_log_init();
+      /* Would be nice to be able to unregister in the fixture */
+      const char* facility = "rlogringbuffer_test";
+      r_log_register(const_cast<char*>(facility), &NR_LOG_TEST);
+    }
+
     void Init() {
       RLogRingBuffer::CreateInstance();
     }
 
     void Free() {
       RLogRingBuffer::DestroyInstance();
     }
 
@@ -249,21 +257,8 @@ TEST_F(RLogRingBufferTest, TestReInit) {
   r_log(NR_LOG_TEST, LOG_INFO, "Test4");
   r_log(NR_LOG_TEST, LOG_INFO, "Test5");
   r_log(NR_LOG_TEST, LOG_INFO, "Test6");
   ReInit();
   std::deque<std::string> logs;
   RLogRingBuffer::GetInstance()->GetAny(0, &logs);
   ASSERT_EQ(0U, logs.size());
 }
-
-int main(int argc, char** argv) {
-  NR_reg_init(NR_REG_MODE_LOCAL);
-  r_log_init();
-  /* Would be nice to be able to register/unregister in the fixture */
-  const char* facility = "rlogringbuffer_test";
-  r_log_register(const_cast<char*>(facility), &NR_LOG_TEST);
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-  return rv;
-}
-
--- a/media/mtransport/test/runnable_utils_unittest.cpp
+++ b/media/mtransport/test/runnable_utils_unittest.cpp
@@ -21,24 +21,22 @@
 #include "nsIServiceManager.h"
 #include "nsISocketTransportService.h"
 
 #include "nsASocketHandler.h"
 #include "nsServiceManagerUtils.h"
 #include "nsThreadUtils.h"
 
 #include "runnable_utils.h"
-#include "mtransport_test_utils.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
 using namespace mozilla;
-MtransportTestUtils *test_utils;
 
 namespace {
 
 class Destructor {
  private:
   ~Destructor() {
     std::cerr << "Destructor called" << std::endl;
     *destroyed_ = true;
@@ -79,19 +77,19 @@ class TargetClass {
 
   void destructor_target_ref(RefPtr<Destructor> destructor) {
   }
 
   int *ran_;
 };
 
 
-class RunnableArgsTest : public ::testing::Test {
+class RunnableArgsTest : public MtransportTest {
  public:
-  RunnableArgsTest() : ran_(0), cl_(&ran_){}
+  RunnableArgsTest() : MtransportTest(), ran_(0), cl_(&ran_){}
 
   void Test1Arg() {
     nsRunnable * r = WrapRunnable(&cl_, &TargetClass::m1, 1);
     r->Run();
     ASSERT_EQ(1, ran_);
   }
 
   void Test2Args() {
@@ -100,21 +98,23 @@ class RunnableArgsTest : public ::testin
     ASSERT_EQ(2, ran_);
   }
 
  private:
   int ran_;
   TargetClass cl_;
 };
 
-class DispatchTest : public ::testing::Test {
+class DispatchTest : public MtransportTest {
  public:
-  DispatchTest() : ran_(0), cl_(&ran_) {}
+  DispatchTest() : MtransportTest(), ran_(0), cl_(&ran_) {}
 
   void SetUp() {
+    MtransportTest::SetUp();
+
     nsresult rv;
     target_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
     ASSERT_TRUE(NS_SUCCEEDED(rv));
   }
 
   void Test1Arg() {
     nsRunnable* r = WrapRunnable(&cl_, &TargetClass::m1, 1);
     target_->Dispatch(r, NS_DISPATCH_SYNC);
@@ -180,26 +180,26 @@ void SetNonMethod(TargetClass *cl, int x
 
 int SetNonMethodRet(TargetClass *cl, int x) {
   cl->m1(x);
 
   return x;
 }
 
 TEST_F(DispatchTest, TestNonMethod) {
-  test_utils->sts_target()->Dispatch(
+  test_utils_->sts_target()->Dispatch(
       WrapRunnableNM(SetNonMethod, &cl_, 10), NS_DISPATCH_SYNC);
 
   ASSERT_EQ(1, ran_);
 }
 
 TEST_F(DispatchTest, TestNonMethodRet) {
   int z;
 
-  test_utils->sts_target()->Dispatch(
+  test_utils_->sts_target()->Dispatch(
       WrapRunnableNMRet(&z, SetNonMethodRet, &cl_, 10), NS_DISPATCH_SYNC);
 
   ASSERT_EQ(1, ran_);
   ASSERT_EQ(10, z);
 }
 
 TEST_F(DispatchTest, TestDestructor) {
   bool destroyed = false;
@@ -220,21 +220,8 @@ TEST_F(DispatchTest, TestDestructorRef) 
                     NS_DISPATCH_SYNC);
   ASSERT_FALSE(destroyed);
   destructor = nullptr;
   ASSERT_TRUE(destroyed);
 }
 
 
 } // end of namespace
-
-
-int main(int argc, char **argv) {
-  test_utils = new MtransportTestUtils();
-
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-  delete test_utils;
-  return rv;
-}
-
--- a/media/mtransport/test/sctp_unittest.cpp
+++ b/media/mtransport/test/sctp_unittest.cpp
@@ -18,28 +18,26 @@
 #include "nsComponentManagerUtils.h"
 #include "nsThreadUtils.h"
 #include "nsXPCOM.h"
 
 #include "transportflow.h"
 #include "transportlayer.h"
 #include "transportlayerloopback.h"
 
-#include "mtransport_test_utils.h"
 #include "runnable_utils.h"
 #include "usrsctp.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
 
 using namespace mozilla;
 
-MtransportTestUtils *test_utils;
 static bool sctp_logging = false;
 static int port_number = 5000;
 
 namespace {
 
 class TransportTestPeer;
 
 class SendPeriodic : public nsITimerCallback {
@@ -58,24 +56,26 @@ class SendPeriodic : public nsITimerCall
   int to_send_;
 };
 
 NS_IMPL_ISUPPORTS(SendPeriodic, nsITimerCallback)
 
 
 class TransportTestPeer : public sigslot::has_slots<> {
  public:
-  TransportTestPeer(std::string name, int local_port, int remote_port)
+  TransportTestPeer(std::string name, int local_port, int remote_port,
+                    MtransportTestUtils* utils)
       : name_(name), connected_(false),
         sent_(0), received_(0),
         flow_(new TransportFlow()),
         loopback_(new TransportLayerLoopback()),
         sctp_(usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP, receive_cb, nullptr, 0, nullptr)),
         timer_(do_CreateInstance(NS_TIMER_CONTRACTID)),
-        periodic_(nullptr) {
+        periodic_(nullptr),
+        test_utils_(utils) {
     std::cerr << "Creating TransportTestPeer; flow=" <<
         static_cast<void *>(flow_.get()) <<
         " local=" << local_port <<
         " remote=" << remote_port << std::endl;
 
     usrsctp_register_address(static_cast<void *>(this));
     int r = usrsctp_set_non_blocking(sctp_, 1);
     EXPECT_GE(r, 0);
@@ -119,25 +119,25 @@ class TransportTestPeer : public sigslot
   }
 
   ~TransportTestPeer() {
     std::cerr << "Destroying sctp connection flow=" <<
         static_cast<void *>(flow_.get()) << std::endl;
     usrsctp_close(sctp_);
     usrsctp_deregister_address(static_cast<void *>(this));
 
-    test_utils->sts_target()->Dispatch(WrapRunnable(this,
+    test_utils_->sts_target()->Dispatch(WrapRunnable(this,
                                                    &TransportTestPeer::Disconnect_s),
                                       NS_DISPATCH_SYNC);
 
     std::cerr << "~TransportTestPeer() completed" << std::endl;
   }
 
   void ConnectSocket(TransportTestPeer *peer) {
-    test_utils->sts_target()->Dispatch(WrapRunnable(
+    test_utils_->sts_target()->Dispatch(WrapRunnable(
         this, &TransportTestPeer::ConnectSocket_s, peer),
                                        NS_DISPATCH_SYNC);
   }
 
   void ConnectSocket_s(TransportTestPeer *peer) {
     loopback_->Connect(peer->loopback_);
 
     ASSERT_EQ((nsresult)NS_OK, flow_->PushLayer(loopback_));
@@ -165,17 +165,17 @@ class TransportTestPeer : public sigslot
 
   void Disconnect() {
     loopback_->Disconnect();
   }
 
 
   void StartTransfer(size_t to_send) {
     periodic_ = new SendPeriodic(this, to_send);
-    timer_->SetTarget(test_utils->sts_target());
+    timer_->SetTarget(test_utils_->sts_target());
     timer_->InitWithCallback(periodic_, 10, nsITimer::TYPE_REPEATING_SLACK);
   }
 
   void SendOne() {
     unsigned char buf[100];
     memset(buf, sent_ & 0xff, sizeof(buf));
 
     struct sctp_sndinfo info;
@@ -210,17 +210,17 @@ class TransportTestPeer : public sigslot
     memcpy(buffer, data, len);
 
     // Uses DISPATCH_NORMAL to avoid possible deadlocks when we're called
     // from MainThread especially during shutdown (same as DataChannels).
     // RUN_ON_THREAD short-circuits if already on the STS thread, which is
     // normal for most transfers outside of connect() and close().  Passes
     // a refptr to flow_ to avoid any async deletion issues (since we can't
     // make 'this' into a refptr as it isn't refcounted)
-    RUN_ON_THREAD(test_utils->sts_target(), WrapRunnableNM(
+    RUN_ON_THREAD(test_utils_->sts_target(), WrapRunnableNM(
         &TransportTestPeer::SendPacket_s, buffer, len, flow_),
                   NS_DISPATCH_NORMAL);
 
     return 0;
   }
 
   void PacketReceived(TransportFlow * flow, const unsigned char* data,
                       size_t len) {
@@ -291,41 +291,36 @@ class TransportTestPeer : public sigslot
   RefPtr<TransportFlow> flow_;
   TransportLayerLoopback *loopback_;
 
   struct sockaddr_conn local_addr_;
   struct sockaddr_conn remote_addr_;
   struct socket *sctp_;
   nsCOMPtr<nsITimer> timer_;
   RefPtr<SendPeriodic> periodic_;
+  MtransportTestUtils* test_utils_;
 };
 
 
 // Implemented here because it calls a method of TransportTestPeer
 NS_IMETHODIMP SendPeriodic::Notify(nsITimer *timer) {
   peer_->SendOne();
   --to_send_;
   if (!to_send_) {
     timer->Cancel();
   }
   return NS_OK;
 }
 
-class TransportTest : public ::testing::Test {
+class SctpTransportTest : public MtransportTest {
  public:
-  TransportTest() {
+  SctpTransportTest() {
   }
 
-  ~TransportTest() {
-    if (p1_)
-      p1_->Disconnect();
-    if (p2_)
-      p2_->Disconnect();
-    delete p1_;
-    delete p2_;
+  ~SctpTransportTest() {
   }
 
   static void debug_printf(const char *format, ...) {
     va_list ap;
 
     va_start(ap, format);
     vprintf(format, ap);
     va_end(ap);
@@ -336,27 +331,36 @@ class TransportTest : public ::testing::
     if (sctp_logging) {
       usrsctp_init(0, &TransportTestPeer::conn_output, debug_printf);
       usrsctp_sysctl_set_sctp_debug_on(0xffffffff);
     } else {
       usrsctp_init(0, &TransportTestPeer::conn_output, nullptr);
     }
   }
 
-  void SetUp() {
+  void TearDown() override {
+    if (p1_)
+      p1_->Disconnect();
+    if (p2_)
+      p2_->Disconnect();
+    delete p1_;
+    delete p2_;
+
+    MtransportTest::TearDown();
   }
 
+
   void ConnectSocket(int p1port = 0, int p2port = 0) {
     if (!p1port)
       p1port = port_number++;
     if (!p2port)
       p2port = port_number++;
 
-    p1_ = new TransportTestPeer("P1", p1port, p2port);
-    p2_ = new TransportTestPeer("P2", p2port, p1port);
+    p1_ = new TransportTestPeer("P1", p1port, p2port, test_utils_);
+    p2_ = new TransportTestPeer("P2", p2port, p1port, test_utils_);
 
     p1_->ConnectSocket(p2_);
     p2_->ConnectSocket(p1_);
     ASSERT_TRUE_WAIT(p1_->connected(), 2000);
     ASSERT_TRUE_WAIT(p2_->connected(), 2000);
   }
 
   void TestTransfer(int expected = 1) {
@@ -367,40 +371,23 @@ class TransportTest : public ::testing::
     std::cerr << "P2 received " << p2_->received() << std::endl;
   }
 
  protected:
   TransportTestPeer *p1_;
   TransportTestPeer *p2_;
 };
 
-TEST_F(TransportTest, TestConnect) {
+TEST_F(SctpTransportTest, TestConnect) {
   ConnectSocket();
 }
 
-TEST_F(TransportTest, TestConnectSymmetricalPorts) {
+TEST_F(SctpTransportTest, TestConnectSymmetricalPorts) {
   ConnectSocket(5002,5002);
 }
 
-TEST_F(TransportTest, TestTransfer) {
+TEST_F(SctpTransportTest, TestTransfer) {
   ConnectSocket();
   TestTransfer(50);
 }
 
 
 }  // end namespace
-
-int main(int argc, char **argv)
-{
-  test_utils = new MtransportTestUtils();
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  for(int i=0; i<argc; i++) {
-    if (!strcmp(argv[i],"-v")) {
-      sctp_logging = true;
-    }
-  }
-
-  int rv = RUN_ALL_TESTS();
-  delete test_utils;
-  return rv;
-}
--- a/media/mtransport/test/simpletokenbucket_unittest.cpp
+++ b/media/mtransport/test/simpletokenbucket_unittest.cpp
@@ -100,16 +100,8 @@ TEST(SimpleTokenBucketTest, TestEmptyThe
 
 TEST(SimpleTokenBucketTest, TestNoOverflow) {
   TestSimpleTokenBucket b(10, 1);
   ASSERT_EQ(10U, b.getTokens(10));
   ASSERT_EQ(0U, b.getTokens(1));
   b.fastForward(50000);
   ASSERT_EQ(10U, b.getTokens(11));
 }
-
-int main(int argc, char** argv) {
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-  return rv;
-}
-
--- a/media/mtransport/test/sockettransportservice_unittest.cpp
+++ b/media/mtransport/test/sockettransportservice_unittest.cpp
@@ -19,28 +19,26 @@
 #include "nsIIOService.h"
 #include "nsIServiceManager.h"
 #include "nsISocketTransportService.h"
 
 #include "nsASocketHandler.h"
 #include "nsServiceManagerUtils.h"
 #include "nsThreadUtils.h"
 
-#include "mtransport_test_utils.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
-MtransportTestUtils *test_utils;
-
 namespace {
-class SocketTransportServiceTest : public ::testing::Test {
+class SocketTransportServiceTest : public MtransportTest {
  public:
-  SocketTransportServiceTest() : received_(0),
+  SocketTransportServiceTest() : MtransportTest(),
+                                 received_(0),
                                  readpipe_(nullptr),
                                  writepipe_(nullptr),
                                  registered_(false) {
   }
 
   ~SocketTransportServiceTest() {
     if (readpipe_)
       PR_Close(readpipe_);
@@ -138,16 +136,18 @@ class SocketHandler : public nsASocketHa
 
  private:
   SocketTransportServiceTest *test_;
 };
 
 NS_IMPL_ISUPPORTS0(SocketHandler)
 
 void SocketTransportServiceTest::SetUp() {
+  MtransportTest::SetUp();
+
   // Get the transport service as a dispatch target
   nsresult rv;
   target_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
   ASSERT_TRUE(NS_SUCCEEDED(rv));
 
   // Get the transport service as a transport service
   stservice_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
   ASSERT_TRUE(NS_SUCCEEDED(rv));
@@ -199,20 +199,8 @@ TEST_F(SocketTransportServiceTest, SendE
 }
 
 TEST_F(SocketTransportServiceTest, SendPacket) {
   SendPacket();
 }
 
 
 }  // end namespace
-
-
-int main(int argc, char **argv) {
-  test_utils = new MtransportTestUtils();
-
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-  delete test_utils;
-  return rv;
-}
--- a/media/mtransport/test/test_nr_socket_unittest.cpp
+++ b/media/mtransport/test/test_nr_socket_unittest.cpp
@@ -20,45 +20,52 @@ extern "C" {
 
 #include "test_nr_socket.h"
 
 #include "nsCOMPtr.h"
 #include "nsNetCID.h"
 #include "nsServiceManagerUtils.h"
 #include "nsAutoPtr.h"
 #include "runnable_utils.h"
-#include "mtransport_test_utils.h"
 
 #include <vector>
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
 #define DATA_BUF_SIZE 1024
 
 namespace mozilla {
 
-class TestNrSocketTest : public ::testing::Test {
+class TestNrSocketTest : public MtransportTest {
  public:
   TestNrSocketTest() :
+    MtransportTest(),
     wait_done_for_main_(false),
     sts_(),
     public_addrs_(),
     private_addrs_(),
     nats_() {
+  }
+
+  void SetUp() override {
+    MtransportTest::SetUp();
+
     // Get the transport service as a dispatch target
     nsresult rv;
     sts_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
     EXPECT_TRUE(NS_SUCCEEDED(rv)) << "Failed to get STS: " << (int)rv;
   }
 
-  ~TestNrSocketTest() {
+  void TearDown() override {
     sts_->Dispatch(WrapRunnable(this, &TestNrSocketTest::TearDown_s),
                    NS_DISPATCH_SYNC);
+
+    MtransportTest::TearDown();
   }
 
   void TearDown_s() {
     public_addrs_.clear();
     private_addrs_.clear();
     nats_.clear();
     sts_ = nullptr;
   }
@@ -849,23 +856,8 @@ TEST_F(TestNrSocketTest, NoConnectivityP
 {
   RefPtr<TestNat> nat(CreatePrivateAddrs(1, "127.0.0.1", IPPROTO_TCP));
   nat->filtering_type_ = TestNat::ENDPOINT_INDEPENDENT;
   nat->mapping_type_ = TestNat::ENDPOINT_INDEPENDENT;
   CreatePublicAddrs(1, "127.0.0.1", IPPROTO_TCP);
 
   ASSERT_FALSE(CheckTcpConnectivity(public_addrs_[0], private_addrs_[0]));
 }
-
-int main(int argc, char **argv)
-{
-  // Inits STS and some other stuff.
-  MtransportTestUtils test_utils;
-
-  NR_reg_init(NR_REG_MODE_LOCAL);
-
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-
-  return rv;
-}
--- a/media/mtransport/test/transport_unittests.cpp
+++ b/media/mtransport/test/transport_unittests.cpp
@@ -30,28 +30,25 @@
 #include "nricemediastream.h"
 #include "transportflow.h"
 #include "transportlayer.h"
 #include "transportlayerdtls.h"
 #include "transportlayerice.h"
 #include "transportlayerlog.h"
 #include "transportlayerloopback.h"
 
-#include "mtransport_test_utils.h"
 #include "runnable_utils.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
 using namespace mozilla;
 MOZ_MTLOG_MODULE("mtransport")
 
-MtransportTestUtils *test_utils;
-
 
 const uint8_t kTlsChangeCipherSpecType = 0x14;
 const uint8_t kTlsHandshakeType =        0x16;
 
 const uint8_t kTlsHandshakeCertificate = 0x0b;
 const uint8_t kTlsHandshakeServerKeyExchange = 0x0c;
 
 const uint8_t kTlsFakeChangeCipherSpec[] = {
@@ -431,34 +428,35 @@ class TlsServerKeyExchangeECDHE {
   }
 
   DataBuffer public_key_;
 };
 
 namespace {
 class TransportTestPeer : public sigslot::has_slots<> {
  public:
-  TransportTestPeer(nsCOMPtr<nsIEventTarget> target, std::string name)
+  TransportTestPeer(nsCOMPtr<nsIEventTarget> target, std::string name, MtransportTestUtils* utils)
       : name_(name), target_(target),
         received_packets_(0),received_bytes_(0),flow_(new TransportFlow(name)),
         loopback_(new TransportLayerLoopback()),
         logging_(new TransportLayerLogging()),
         lossy_(new TransportLayerLossy()),
         dtls_(new TransportLayerDtls()),
         identity_(DtlsIdentity::Generate()),
         ice_ctx_(NrIceCtx::Create(name,
                                   name == "P2" ?
                                   TransportLayerDtls::CLIENT :
                                   TransportLayerDtls::SERVER)),
         streams_(), candidates_(),
         peer_(nullptr),
         gathering_complete_(false),
         enabled_cipersuites_(),
         disabled_cipersuites_(),
-        reuse_dhe_key_(false) {
+        reuse_dhe_key_(false),
+        test_utils_(utils) {
     std::vector<NrIceStunServer> stun_servers;
     UniquePtr<NrIceStunServer> server(NrIceStunServer::Create(
         std::string((char *)"stun.services.mozilla.com"), 3478));
     stun_servers.push_back(*server);
     EXPECT_TRUE(NS_SUCCEEDED(ice_ctx_->SetStunServers(stun_servers)));
 
     dtls_->SetIdentity(identity_);
     dtls_->SetRole(name == "P2" ?
@@ -469,17 +467,17 @@ class TransportTestPeer : public sigslot
                                              fingerprint_,
                                              sizeof(fingerprint_),
                                              &fingerprint_len_);
     EXPECT_TRUE(NS_SUCCEEDED(res));
     EXPECT_EQ(20u, fingerprint_len_);
   }
 
   ~TransportTestPeer() {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
       WrapRunnable(this, &TransportTestPeer::DestroyFlow),
       NS_DISPATCH_SYNC);
   }
 
 
   void DestroyFlow() {
     if (flow_) {
       loopback_->Disconnect();
@@ -586,17 +584,17 @@ class TransportTestPeer : public sigslot
     }
     for (auto it = disabled_cipersuites_.begin();
          it != disabled_cipersuites_.end(); ++it) {
       SSL_CipherPrefSet(fd, *it, PR_FALSE);
     }
   }
 
   void ConnectSocket(TransportTestPeer *peer) {
-    RUN_ON_THREAD(test_utils->sts_target(),
+    RUN_ON_THREAD(test_utils_->sts_target(),
                   WrapRunnable(this, & TransportTestPeer::ConnectSocket_s,
                                peer),
                   NS_DISPATCH_SYNC);
   }
 
   void InitIce() {
     nsresult res;
 
@@ -625,28 +623,28 @@ class TransportTestPeer : public sigslot
     ice_->SetParameters(ice_ctx_, stream, 1);
 
     // Assemble the stack
     nsAutoPtr<std::queue<mozilla::TransportLayer *> > layers(
       new std::queue<mozilla::TransportLayer *>);
     layers->push(ice_);
     layers->push(dtls_);
 
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
       WrapRunnableRet(&res, flow_, &TransportFlow::PushLayers, layers),
       NS_DISPATCH_SYNC);
 
     ASSERT_EQ((nsresult)NS_OK, res);
 
     // Listen for media events
     flow_->SignalPacketReceived.connect(this, &TransportTestPeer::PacketReceived);
     flow_->SignalStateChange.connect(this, &TransportTestPeer::StateChanged);
 
     // Start gathering
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&res, ice_ctx_, &NrIceCtx::StartGathering),
         NS_DISPATCH_SYNC);
     ASSERT_TRUE(NS_SUCCEEDED(res));
   }
 
   void ConnectIce(TransportTestPeer *peer) {
     peer_ = peer;
 
@@ -676,41 +674,41 @@ class TransportTestPeer : public sigslot
 
     // Don't send to the other side
     if (!peer_) {
       gathering_complete_ = true;
       return;
     }
 
     // First send attributes
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
       WrapRunnableRet(&res, peer_->ice_ctx_,
                       &NrIceCtx::ParseGlobalAttributes,
                       ice_ctx_->GetGlobalAttributes()),
       NS_DISPATCH_SYNC);
     ASSERT_TRUE(NS_SUCCEEDED(res));
 
     for (size_t i=0; i<streams_.size(); ++i) {
-      test_utils->sts_target()->Dispatch(
+      test_utils_->sts_target()->Dispatch(
         WrapRunnableRet(&res, peer_->streams_[i], &NrIceMediaStream::ParseAttributes,
                         candidates_[streams_[i]->name()]), NS_DISPATCH_SYNC);
 
       ASSERT_TRUE(NS_SUCCEEDED(res));
     }
 
     // Start checks on the other peer.
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
       WrapRunnableRet(&res, peer_->ice_ctx_, &NrIceCtx::StartChecks),
       NS_DISPATCH_SYNC);
     ASSERT_TRUE(NS_SUCCEEDED(res));
   }
 
   TransportResult SendPacket(const unsigned char* data, size_t len) {
     TransportResult ret;
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
       WrapRunnableRet(&ret, flow_, &TransportFlow::SendPacket, data, len),
       NS_DISPATCH_SYNC);
 
     return ret;
   }
 
 
   void StateChanged(TransportFlow *flow, TransportLayer::State state) {
@@ -752,17 +750,17 @@ class TransportTestPeer : public sigslot
 
   void SetReuseECDHEKey() {
     reuse_dhe_key_ = true;
   }
 
   TransportLayer::State state() {
     TransportLayer::State tstate;
 
-    RUN_ON_THREAD(test_utils->sts_target(),
+    RUN_ON_THREAD(test_utils_->sts_target(),
                   WrapRunnableRet(&tstate, flow_, &TransportFlow::state));
 
     return tstate;
   }
 
   bool connected() {
     return state() == TransportLayer::TS_OPEN;
   }
@@ -773,30 +771,30 @@ class TransportTestPeer : public sigslot
 
   size_t receivedPackets() { return received_packets_; }
 
   size_t receivedBytes() { return received_bytes_; }
 
   uint16_t cipherSuite() const {
     nsresult rv;
     uint16_t cipher;
-    RUN_ON_THREAD(test_utils->sts_target(),
+    RUN_ON_THREAD(test_utils_->sts_target(),
                   WrapRunnableRet(&rv, dtls_, &TransportLayerDtls::GetCipherSuite,
                                   &cipher));
 
     if (NS_FAILED(rv)) {
       return TLS_NULL_WITH_NULL_NULL; // i.e., not good
     }
     return cipher;
   }
 
   uint16_t srtpCipher() const {
     nsresult rv;
     uint16_t cipher;
-    RUN_ON_THREAD(test_utils->sts_target(),
+    RUN_ON_THREAD(test_utils_->sts_target(),
                   WrapRunnableRet(&rv, dtls_, &TransportLayerDtls::GetSrtpCipher,
                                   &cipher));
     if (NS_FAILED(rv)) {
       return 0; // the SRTP equivalent of TLS_NULL_WITH_NULL_NULL
     }
     return cipher;
   }
 
@@ -817,51 +815,55 @@ class TransportTestPeer : public sigslot
   std::map<std::string, std::vector<std::string> > candidates_;
   TransportTestPeer *peer_;
   bool gathering_complete_;
   unsigned char fingerprint_[TransportLayerDtls::kMaxDigestLength];
   size_t fingerprint_len_;
   std::vector<uint16_t> enabled_cipersuites_;
   std::vector<uint16_t> disabled_cipersuites_;
   bool reuse_dhe_key_;
+  MtransportTestUtils* test_utils_;
 };
 
 
-class TransportTest : public ::testing::Test {
+class TransportTest : public MtransportTest {
  public:
   TransportTest() {
     fds_[0] = nullptr;
     fds_[1] = nullptr;
   }
 
-  ~TransportTest() {
+  void TearDown() override {
     delete p1_;
     delete p2_;
 
     //    Can't detach these
     //    PR_Close(fds_[0]);
     //    PR_Close(fds_[1]);
+    MtransportTest::TearDown();
   }
 
   void DestroyPeerFlows() {
     p1_->DisconnectDestroyFlow();
     p2_->DisconnectDestroyFlow();
   }
 
-  void SetUp() {
+  void SetUp() override {
+    MtransportTest::SetUp();
+
     nsresult rv;
     target_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
     ASSERT_TRUE(NS_SUCCEEDED(rv));
 
     Reset();
   }
 
   void Reset() {
-    p1_ = new TransportTestPeer(target_, "P1");
-    p2_ = new TransportTestPeer(target_, "P2");
+    p1_ = new TransportTestPeer(target_, "P1", test_utils_);
+    p2_ = new TransportTestPeer(target_, "P2", test_utils_);
   }
 
   void SetupSrtp() {
     p1_->SetupSrtp();
     p2_->SetupSrtp();
   }
 
   void SetDtlsPeer(int digests = 1, unsigned int damage = 0) {
@@ -936,20 +938,20 @@ class TransportTest : public ::testing::
 
     std::cerr << "Received == " << p2_->receivedPackets() << " packets" << std::endl;
     ASSERT_TRUE_WAIT(count == p2_->receivedPackets(), 10000);
     ASSERT_TRUE((count * sizeof(buf)) == p2_->receivedBytes());
   }
 
  protected:
   void ConnectSocketInternal() {
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
       WrapRunnable(p1_, &TransportTestPeer::ConnectSocket, p2_),
       NS_DISPATCH_SYNC);
-    test_utils->sts_target()->Dispatch(
+    test_utils_->sts_target()->Dispatch(
       WrapRunnable(p2_, &TransportTestPeer::ConnectSocket, p1_),
       NS_DISPATCH_SYNC);
   }
 
   PRFileDesc *fds_[2];
   TransportTestPeer *p1_;
   TransportTestPeer *p2_;
   nsCOMPtr<nsIEventTarget> target_;
@@ -1319,22 +1321,8 @@ TEST(PushTests, LayersFail) {
   rv = flow->PushLayers(layers);
 
   ASSERT_TRUE(NS_FAILED(rv));
   ASSERT_EQ(true, destroyed2);
   ASSERT_EQ(true, destroyed3);
 }
 
 }  // end namespace
-
-int main(int argc, char **argv)
-{
-  test_utils = new MtransportTestUtils();
-
-  NSS_NoDB_Init(nullptr);
-  NSS_SetDomesticPolicy();
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-  delete test_utils;
-  return rv;
-}
--- a/media/mtransport/test/turn_unittest.cpp
+++ b/media/mtransport/test/turn_unittest.cpp
@@ -48,17 +48,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 #include "nspr.h"
 #include "nss.h"
 #include "ssl.h"
 
 #include "mozilla/Scoped.h"
 #include "nsThreadUtils.h"
 #include "nsXPCOM.h"
 
-#include "mtransport_test_utils.h"
 #include "runnable_utils.h"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
 #define USE_TURN
 
@@ -77,43 +76,41 @@ extern "C" {
 #include "stun_client_ctx.h"
 #include "turn_client_ctx.h"
 }
 
 #include "nricemediastream.h"
 #include "nricectx.h"
 
 
-MtransportTestUtils *test_utils;
-
 using namespace mozilla;
 
-std::string g_turn_server;
-std::string g_turn_user;
-std::string g_turn_password;
+static std::string kDummyTurnServer("192.0.2.1");  // From RFC 5737
 
-std::string kDummyTurnServer("192.0.2.1");  // From RFC 5737
-
-class TurnClient : public ::testing::Test {
+class TurnClient : public MtransportTest {
  public:
   TurnClient()
-      : turn_server_(g_turn_server),
+      : MtransportTest(),
         real_socket_(nullptr),
         net_socket_(nullptr),
         buffered_socket_(nullptr),
         net_fd_(nullptr),
         turn_ctx_(nullptr),
         allocated_(false),
         received_(0),
         protocol_(IPPROTO_UDP) {
   }
 
   ~TurnClient() {
   }
 
+  static void SetUpTestCase() {
+    NrIceCtx::Init(false, false, false);
+  }
+
   void SetTcp() {
     protocol_ = IPPROTO_TCP;
   }
 
   void Init_s() {
     int r;
     nr_transport_addr addr;
     r = nr_ip4_port_to_transport_addr(0, 0, protocol_, &addr);
@@ -132,21 +129,21 @@ class TurnClient : public ::testing::Tes
       net_socket_ = real_socket_;
     }
 
     r = nr_str_port_to_transport_addr(turn_server_.c_str(), 3478,
       protocol_, &addr);
     ASSERT_EQ(0, r);
 
     std::vector<unsigned char> password_vec(
-        g_turn_password.begin(), g_turn_password.end());
+        turn_password_.begin(), turn_password_.end());
     Data password;
     INIT_DATA(password, &password_vec[0], password_vec.size());
     r = nr_turn_client_ctx_create("test", net_socket_,
-                                  g_turn_user.c_str(),
+                                  turn_user_.c_str(),
                                   &password,
                                   &addr, &turn_ctx_);
     ASSERT_EQ(0, r);
 
     r = nr_socket_getfd(net_socket_, &net_fd_);
     ASSERT_EQ(0, r);
 
     NR_ASYNC_WAIT(net_fd_, NR_ASYNC_WAIT_READ, socket_readable_cb,
@@ -158,33 +155,33 @@ class TurnClient : public ::testing::Tes
     if (net_fd_) {
       NR_ASYNC_CANCEL(net_fd_, NR_ASYNC_WAIT_READ);
     }
 
     nr_socket_destroy(&buffered_socket_);
   }
 
   void TearDown() {
-    RUN_ON_THREAD(test_utils->sts_target(),
+    RUN_ON_THREAD(test_utils_->sts_target(),
                   WrapRunnable(this, &TurnClient::TearDown_s),
                   NS_DISPATCH_SYNC);
   }
 
   void Allocate_s() {
     Init_s();
     ASSERT_TRUE(turn_ctx_);
 
     int r = nr_turn_client_allocate(turn_ctx_,
                                     allocate_success_cb,
                                     this);
     ASSERT_EQ(0, r);
   }
 
   void Allocate(bool expect_success=true) {
-    RUN_ON_THREAD(test_utils->sts_target(),
+    RUN_ON_THREAD(test_utils_->sts_target(),
                   WrapRunnable(this, &TurnClient::Allocate_s),
                   NS_DISPATCH_SYNC);
 
     if (expect_success) {
       ASSERT_TRUE_WAIT(allocated_, 5000);
     }
     else {
       PR_Sleep(10000);
@@ -214,17 +211,17 @@ class TurnClient : public ::testing::Tes
     ASSERT_TRUE(turn_ctx_);
 
     std::cerr << "De-Allocating..." << std::endl;
     int r = nr_turn_client_deallocate(turn_ctx_);
     ASSERT_EQ(0, r);
   }
 
   void Deallocate() {
-    RUN_ON_THREAD(test_utils->sts_target(),
+    RUN_ON_THREAD(test_utils_->sts_target(),
                   WrapRunnable(this, &TurnClient::Deallocate_s),
                   NS_DISPATCH_SYNC);
   }
 
   void RequestPermission_s(const std::string& target) {
     nr_transport_addr addr;
     int r;
 
@@ -243,17 +240,17 @@ class TurnClient : public ::testing::Tes
                                       &addr);
     ASSERT_EQ(0, r);
 
     r = nr_turn_client_ensure_perm(turn_ctx_, &addr);
     ASSERT_EQ(0, r);
   }
 
   void RequestPermission(const std::string& target) {
-    RUN_ON_THREAD(test_utils->sts_target(),
+    RUN_ON_THREAD(test_utils_->sts_target(),
                   WrapRunnable(this, &TurnClient::RequestPermission_s, target),
                   NS_DISPATCH_SYNC);
 
   }
 
   void Readable(NR_SOCKET s, int how, void *arg) {
     // Re-arm
     std::cerr << "Socket is readable" << std::endl;
@@ -341,17 +338,17 @@ class TurnClient : public ::testing::Tes
                                             test, sizeof(test), 0,
                                             &addr);
     if (expect_return >= 0) {
       ASSERT_EQ(expect_return, r);
     }
   }
 
   void SendTo(const std::string& target, int expect_return=0) {
-    RUN_ON_THREAD(test_utils->sts_target(),
+    RUN_ON_THREAD(test_utils_->sts_target(),
                   WrapRunnable(this, &TurnClient::SendTo_s, target,
                                expect_return),
                   NS_DISPATCH_SYNC);
   }
 
   int received() const { return received_; }
 
   static void socket_readable_cb(NR_SOCKET s, int how, void *arg) {
@@ -371,49 +368,67 @@ class TurnClient : public ::testing::Tes
   nr_turn_client_ctx *turn_ctx_;
   std::string relay_addr_;
   bool allocated_;
   int received_;
   int protocol_;
 };
 
 TEST_F(TurnClient, Allocate) {
+  if (WarnIfTurnNotConfigured())
+    return;
+
   Allocate();
 }
 
 TEST_F(TurnClient, AllocateTcp) {
+  if (WarnIfTurnNotConfigured())
+    return;
+
   SetTcp();
   Allocate();
 }
 
 TEST_F(TurnClient, AllocateAndHold) {
+  if (WarnIfTurnNotConfigured())
+    return;
+
   Allocate();
   PR_Sleep(20000);
   ASSERT_TRUE(turn_ctx_->state == NR_TURN_CLIENT_STATE_ALLOCATED);
 }
 
 TEST_F(TurnClient, SendToSelf) {
+  if (WarnIfTurnNotConfigured())
+    return;
+
   Allocate();
   SendTo(relay_addr_);
   ASSERT_TRUE_WAIT(received() == 100, 5000);
   SendTo(relay_addr_);
   ASSERT_TRUE_WAIT(received() == 200, 1000);
 }
 
 
 TEST_F(TurnClient, SendToSelfTcp) {
+  if (WarnIfTurnNotConfigured())
+    return;
+
   SetTcp();
   Allocate();
   SendTo(relay_addr_);
   ASSERT_TRUE_WAIT(received() == 100, 5000);
   SendTo(relay_addr_);
   ASSERT_TRUE_WAIT(received() == 200, 1000);
 }
 
 TEST_F(TurnClient, PermissionDenied) {
+  if (WarnIfTurnNotConfigured())
+    return;
+
   Allocate();
   RequestPermission(relay_addr_);
   PR_Sleep(1000);
 
   /* Fake a 403 response */
   nr_turn_permission *perm;
   perm = STAILQ_FIRST(&turn_ctx_->permissions);
   ASSERT_TRUE(perm);
@@ -427,91 +442,47 @@ TEST_F(TurnClient, PermissionDenied) {
   ASSERT_TRUE(received() == 0);
 
   //TODO: We should check if we can still send to a second destination, but
   //      we would need a second TURN client as one client can only handle one
   //      allocation (maybe as part of bug 1128128 ?).
 }
 
 TEST_F(TurnClient, DeallocateReceiveFailure) {
+  if (WarnIfTurnNotConfigured())
+    return;
+
   Allocate();
   SendTo(relay_addr_);
   ASSERT_TRUE_WAIT(received() == 100, 5000);
   Deallocate();
   turn_ctx_->state = NR_TURN_CLIENT_STATE_ALLOCATED;
   SendTo(relay_addr_);
   PR_Sleep(1000);
   ASSERT_TRUE(received() == 100);
 }
 
 TEST_F(TurnClient, DeallocateReceiveFailureTcp) {
+  if (WarnIfTurnNotConfigured())
+    return;
+
   SetTcp();
   Allocate();
   SendTo(relay_addr_);
   ASSERT_TRUE_WAIT(received() == 100, 5000);
   Deallocate();
   turn_ctx_->state = NR_TURN_CLIENT_STATE_ALLOCATED;
   /* Either the connection got closed by the TURN server already, then the send
    * is going to fail, which we simply ignore. Or the connection is still alive
    * and we cand send the data, but it should not get forwarded to us. In either
    * case we should not receive more data. */
   SendTo(relay_addr_, -1);
   PR_Sleep(1000);
   ASSERT_TRUE(received() == 100);
 }
 
 TEST_F(TurnClient, AllocateDummyServer) {
+  if (WarnIfTurnNotConfigured())
+    return;
+
   turn_server_ = kDummyTurnServer;
   Allocate(false);
 }
-
-static std::string get_environment(const char *name) {
-  char *value = getenv(name);
-
-  if (!value)
-    return "";
-
-  return value;
-}
-
-int main(int argc, char **argv)
-{
-  g_turn_server = get_environment("TURN_SERVER_ADDRESS");
-  g_turn_user = get_environment("TURN_SERVER_USER");
-  g_turn_password = get_environment("TURN_SERVER_PASSWORD");
-
-  if (g_turn_server.empty() ||
-      g_turn_user.empty(),
-      g_turn_password.empty()) {
-    printf(
-        "Set TURN_SERVER_ADDRESS, TURN_SERVER_USER, and TURN_SERVER_PASSWORD\n"
-        "environment variables to run this test\n");
-    return 0;
-  }
-  {
-    nr_transport_addr addr;
-    if (nr_str_port_to_transport_addr(g_turn_server.c_str(), 3478,
-                                      IPPROTO_UDP, &addr)) {
-      printf("Invalid TURN_SERVER_ADDRESS \"%s\". Only IP numbers supported.\n",
-             g_turn_server.c_str());
-      return 0;
-    }
-  }
-  test_utils = new MtransportTestUtils();
-  NSS_NoDB_Init(nullptr);
-  NSS_SetDomesticPolicy();
-
-  // Set up the ICE registry, etc.
-  // TODO(ekr@rtfm.com): Clean up
-  std::string dummy("dummy");
-  RUN_ON_THREAD(test_utils->sts_target(),
-                WrapRunnableNM(&NrIceCtx::Create,
-                               dummy, false, false, false, false, false,
-                               NrIceCtx::ICE_POLICY_ALL),
-                NS_DISPATCH_SYNC);
-
-  // Start the tests
-  ::testing::InitGoogleTest(&argc, argv);
-
-  int rv = RUN_ALL_TESTS();
-  delete test_utils;
-  return rv;
-}
--- a/media/webrtc/signaling/test/jsep_session_unittest.cpp
+++ b/media/webrtc/signaling/test/jsep_session_unittest.cpp
@@ -30,16 +30,18 @@
 #include "signaling/src/jsep/JsepSessionImpl.h"
 #include "signaling/src/jsep/JsepTrack.h"
 
 #include "mtransport_test_utils.h"
 
 #include "FakeIPC.h"
 #include "FakeIPC.cpp"
 
+#include "TestHarness.h"
+
 namespace mozilla {
 static std::string kAEqualsCandidate("a=candidate:");
 const static size_t kNumCandidatesPerComponent = 3;
 
 class JsepSessionTestBase : public ::testing::Test
 {
 };
 
--- a/media/webrtc/signaling/test/jsep_track_unittest.cpp
+++ b/media/webrtc/signaling/test/jsep_track_unittest.cpp
@@ -17,16 +17,18 @@
 #include "signaling/src/sdp/SipccSdp.h"
 #include "signaling/src/sdp/SdpHelper.h"
 
 #include "mtransport_test_utils.h"
 
 #include "FakeIPC.h"
 #include "FakeIPC.cpp"
 
+#include "TestHarness.h"
+
 namespace mozilla {
 
 class JsepTrackTest : public ::testing::Test
 {
   public:
     JsepTrackTest() {}
 
     std::vector<JsepCodecDescription*>
--- a/media/webrtc/signaling/test/mediapipeline_unittest.cpp
+++ b/media/webrtc/signaling/test/mediapipeline_unittest.cpp
@@ -38,16 +38,18 @@
 
 #include "FakeIPC.h"
 #include "FakeIPC.cpp"
 
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 #include "gtest_utils.h"
 
+#include "TestHarness.h"
+
 using namespace mozilla;
 MOZ_MTLOG_MODULE("mediapipeline")
 
 MtransportTestUtils *test_utils;
 
 namespace {
 
 class TransportInfo {
@@ -694,16 +696,17 @@ TEST_F(MediaPipelineTest, TestAudioSendE
   // Filter is empty, so should drop everything.
   ASSERT_EQ(0, p2_.GetAudioRtpCountReceived());
 }
 
 }  // end namespace
 
 
 int main(int argc, char **argv) {
+  ScopedXPCOM xpcom("mediapipeline_unittest");
   test_utils = new MtransportTestUtils();
   // Start the tests
   NSS_NoDB_Init(nullptr);
   NSS_SetDomesticPolicy();
   ::testing::InitGoogleTest(&argc, argv);
 
   int rv = RUN_ALL_TESTS();
   delete test_utils;
--- a/media/webrtc/signaling/test/sdp_unittests.cpp
+++ b/media/webrtc/signaling/test/sdp_unittests.cpp
@@ -42,16 +42,18 @@ extern "C" {
 #ifdef CRLF
 #undef CRLF
 #endif
 #define CRLF "\r\n"
 
 #include "FakeIPC.h"
 #include "FakeIPC.cpp"
 
+#include "TestHarness.h"
+
 using namespace mozilla;
 
 namespace test {
 
 static bool SetupGlobalThread() {
   if (!gThread) {
     nsIThread *thread;
 
@@ -4231,16 +4233,18 @@ TEST(NewSdpTestNoFixture, CheckRidSerial
     rid.Serialize(os);
     ASSERT_EQ("foo send pt=96;max-br=30000", os.str());
   }
 }
 
 } // End namespace test.
 
 int main(int argc, char **argv) {
+  ScopedXPCOM xpcom("sdp_unittests");
+
   test_utils = new MtransportTestUtils();
   NSS_NoDB_Init(nullptr);
   NSS_SetDomesticPolicy();
 
   ::testing::InitGoogleTest(&argc, argv);
   int result = RUN_ALL_TESTS();
 
   PeerConnectionCtx::Destroy();