Use gMock matchers in the linear solver and linear algebra tests

Element-wise loops and norm comparisons in the linear solver,
preconditioner, Schur complement and small BLAS tests report little
beyond the failing line.

Compare matrices and vectors using matchers that print the compared
values and locate mismatches, and trace loops over test cases.

Change-Id: I33d22b337844c143a3bdcb1dbc24980f4a5e867a
diff --git a/internal/ceres/block_jacobi_preconditioner_test.cc b/internal/ceres/block_jacobi_preconditioner_test.cc
index 98ddca1..fd71b6b 100644
--- a/internal/ceres/block_jacobi_preconditioner_test.cc
+++ b/internal/ceres/block_jacobi_preconditioner_test.cc
@@ -35,9 +35,12 @@
 #include <vector>
 
 #include "Eigen/Dense"
+#include "absl/strings/str_format.h"
 #include "ceres/block_random_access_diagonal_matrix.h"
 #include "ceres/block_sparse_matrix.h"
 #include "ceres/linear_least_squares_problems.h"
+#include "ceres/test_util.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
@@ -60,6 +63,7 @@
   preconditioner_options.context = &context;
 
   for (int trial = 0; trial < kNumtrials; ++trial) {
+    SCOPED_TRACE(absl::StrFormat("trial %d", trial));
     auto jacobian = BlockSparseMatrix::CreateRandomMatrix(options, prng);
     Vector diagonal = Vector::Ones(jacobian->num_cols());
     Matrix dense_jacobian;
@@ -85,10 +89,9 @@
               .block(r, c, block_size, block_size);
       Matrix expected_block = hessian.block(
           bs->cols[i].position, bs->cols[i].position, block_size, block_size);
-      const double residual = (actual_block_inverse * expected_block -
-                               Matrix::Identity(block_size, block_size))
-                                  .norm();
-      EXPECT_NEAR(residual, 0.0, 1e-12) << "Block: " << i;
+      EXPECT_THAT(actual_block_inverse * expected_block,
+                  NormNear(Matrix::Identity(block_size, block_size), 1e-12))
+          << "Block: " << i;
     }
     options.num_col_blocks++;
     options.num_row_blocks++;
@@ -113,6 +116,7 @@
   preconditioner_options.context = &context;
 
   for (int trial = 0; trial < kNumtrials; ++trial) {
+    SCOPED_TRACE(absl::StrFormat("trial %d", trial));
     auto jacobian =
         CompressedRowSparseMatrix::CreateRandomMatrix(options, prng);
     Vector diagonal = Vector::Ones(jacobian->num_cols());
@@ -143,10 +147,9 @@
       ConstMatrixRef actual_block_inverse(
           m.values() + m.rows()[col], block_size, block_size);
       Matrix expected_block = hessian.block(col, col, block_size, block_size);
-      const double residual = (actual_block_inverse * expected_block -
-                               Matrix::Identity(block_size, block_size))
-                                  .norm();
-      EXPECT_NEAR(residual, 0.0, 1e-12) << "Block: " << i;
+      EXPECT_THAT(actual_block_inverse * expected_block,
+                  NormNear(Matrix::Identity(block_size, block_size), 1e-12))
+          << "Block: " << i;
       col += block_size;
     }
     options.num_col_blocks++;
diff --git a/internal/ceres/conjugate_gradients_solver_test.cc b/internal/ceres/conjugate_gradients_solver_test.cc
index 50403a1..d18666e 100644
--- a/internal/ceres/conjugate_gradients_solver_test.cc
+++ b/internal/ceres/conjugate_gradients_solver_test.cc
@@ -38,12 +38,16 @@
 #include "ceres/eigen.h"
 #include "ceres/linear_solver.h"
 #include "ceres/preconditioner.h"
+#include "ceres/test_util.h"
 #include "ceres/triplet_sparse_matrix.h"
 #include "ceres/types.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
 
+using ::testing::DoubleEq;
+
 TEST(ConjugateGradientTest, Solves3x3IdentitySystem) {
   double diagonal[] = {1.0, 1.0, 1.0};
   std::unique_ptr<TripletSparseMatrix> A(
@@ -82,9 +86,7 @@
   EXPECT_EQ(summary.termination_type, LinearSolverTerminationType::SUCCESS);
   ASSERT_EQ(summary.num_iterations, 1);
 
-  ASSERT_DOUBLE_EQ(1, x(0));
-  ASSERT_DOUBLE_EQ(2, x(1));
-  ASSERT_DOUBLE_EQ(3, x(2));
+  EXPECT_THAT(x, MatrixPointwise(DoubleEq(), Eigen::Vector3d(1.0, 2.0, 3.0)));
 }
 
 TEST(ConjugateGradientTest, Solves3x3SymmetricSystem) {
@@ -147,9 +149,7 @@
 
   EXPECT_EQ(summary.termination_type, LinearSolverTerminationType::SUCCESS);
 
-  ASSERT_DOUBLE_EQ(0, x(0));
-  ASSERT_DOUBLE_EQ(1, x(1));
-  ASSERT_DOUBLE_EQ(2, x(2));
+  EXPECT_THAT(x, MatrixPointwise(DoubleEq(), Eigen::Vector3d(0.0, 1.0, 2.0)));
 }
 
 }  // namespace ceres::internal
diff --git a/internal/ceres/dense_cholesky_test.cc b/internal/ceres/dense_cholesky_test.cc
index 5ff4e9c..0218b50 100644
--- a/internal/ceres/dense_cholesky_test.cc
+++ b/internal/ceres/dense_cholesky_test.cc
@@ -39,11 +39,13 @@
 
 #include "Eigen/Core"
 #include "Eigen/Dense"
+#include "absl/strings/str_format.h"
 #include "ceres/context_impl.h"
 #include "ceres/eigen.h"
 #include "ceres/internal/config.h"
 #include "ceres/iterative_refiner.h"
 #include "ceres/linear_solver.h"
+#include "ceres/test_util.h"
 #include "ceres/types.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -95,6 +97,7 @@
   const int kMaxNumCols = 10;
   for (int num_cols = kMinNumCols; num_cols < kMaxNumCols; ++num_cols) {
     for (int trial = 0; trial < kNumTrials; ++trial) {
+      SCOPED_TRACE(absl::StrFormat("%d columns, trial %d", num_cols, trial));
       const MatrixType a = MatrixType::Random(num_cols, num_cols);
       MatrixType lhs = a.transpose() * a;
       lhs += VectorType::Ones(num_cols).asDiagonal();
@@ -107,11 +110,9 @@
       summary.termination_type = dense_cholesky->FactorAndSolve(
           num_cols, lhs.data(), rhs.data(), actual.data(), &summary.message);
       EXPECT_EQ(summary.termination_type, LinearSolverTerminationType::SUCCESS);
-      EXPECT_NEAR((x - actual).norm() / x.norm(),
-                  0.0,
-                  std::numeric_limits<double>::epsilon() * 10)
-          << "\nexpected: " << x.transpose()
-          << "\nactual  : " << actual.transpose();
+      EXPECT_THAT(
+          actual,
+          RelativeNormNear(x, std::numeric_limits<double>::epsilon() * 10));
     }
   }
 }
diff --git a/internal/ceres/dense_linear_solver_test.cc b/internal/ceres/dense_linear_solver_test.cc
index c35c4ee..446d582 100644
--- a/internal/ceres/dense_linear_solver_test.cc
+++ b/internal/ceres/dense_linear_solver_test.cc
@@ -41,8 +41,10 @@
 #include "ceres/internal/config.h"
 #include "ceres/linear_least_squares_problems.h"
 #include "ceres/linear_solver.h"
+#include "ceres/test_util.h"
 #include "ceres/triplet_sparse_matrix.h"
 #include "ceres/types.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
@@ -101,15 +103,10 @@
     normal_lhs += diagonal.array().square().matrix().asDiagonal();
   }
 
-  Vector actual_normal_rhs = normal_lhs * solution;
-
-  const double normalized_residual =
-      (normal_rhs - actual_normal_rhs).norm() / normal_rhs.norm();
-
-  EXPECT_NEAR(
-      normalized_residual, 0.0, 10 * std::numeric_limits<double>::epsilon())
-      << "\nexpected: " << normal_rhs.transpose()
-      << "\nactual: " << actual_normal_rhs.transpose();
+  const Vector actual_normal_rhs = normal_lhs * solution;
+  EXPECT_THAT(actual_normal_rhs,
+              RelativeNormNear(normal_rhs,
+                               10 * std::numeric_limits<double>::epsilon()));
 }
 
 namespace {
diff --git a/internal/ceres/dense_qr_test.cc b/internal/ceres/dense_qr_test.cc
index b9971e6..dfb915e 100644
--- a/internal/ceres/dense_qr_test.cc
+++ b/internal/ceres/dense_qr_test.cc
@@ -37,8 +37,10 @@
 #include <vector>
 
 #include "Eigen/Dense"
+#include "absl/strings/str_format.h"
 #include "ceres/eigen.h"
 #include "ceres/linear_solver.h"
+#include "ceres/test_util.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
@@ -85,6 +87,8 @@
          num_rows < kMaxRowsFactor * num_cols;
          ++num_rows) {
       for (int trial = 0; trial < kNumTrials; ++trial) {
+        SCOPED_TRACE(absl::StrFormat(
+            "%d rows, %d columns, trial %d", num_rows, num_cols, trial));
         MatrixType lhs = MatrixType::Random(num_rows, num_cols);
         Vector x = VectorType::Random(num_cols);
         Vector rhs = lhs * x;
@@ -98,9 +102,7 @@
                                                             &summary.message);
         ASSERT_EQ(summary.termination_type,
                   LinearSolverTerminationType::SUCCESS);
-        ASSERT_NEAR((x - actual).norm() / x.norm(), 0.0, kEpsilon)
-            << "\nexpected: " << x.transpose()
-            << "\nactual  : " << actual.transpose();
+        ASSERT_THAT(actual, RelativeNormNear(x, kEpsilon));
       }
     }
   }
@@ -124,6 +126,6 @@
 
 }  // namespace
 
-INSTANTIATE_TEST_SUITE_P(_, DenseQRTest, MakeValues(), ParamInfoToString);
+INSTANTIATE_TEST_SUITE_P(DenseQR, DenseQRTest, MakeValues(), ParamInfoToString);
 
 }  // namespace ceres::internal
diff --git a/internal/ceres/dogleg_strategy_test.cc b/internal/ceres/dogleg_strategy_test.cc
index e3856cc..1e8bbd2 100644
--- a/internal/ceres/dogleg_strategy_test.cc
+++ b/internal/ceres/dogleg_strategy_test.cc
@@ -36,10 +36,14 @@
 #include "ceres/dense_qr_solver.h"
 #include "ceres/eigen.h"
 #include "ceres/linear_solver.h"
+#include "ceres/test_util.h"
 #include "ceres/trust_region_strategy.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
+
+using ::testing::DoubleNear;
 namespace {
 
 class Fixture : public testing::Test {
@@ -181,12 +185,9 @@
       strategy.ComputeStep(pso, jacobian_.get(), residual_.data(), x_.data());
 
   EXPECT_NE(summary.termination_type, LinearSolverTerminationType::FAILURE);
-  EXPECT_NEAR(x_(0), 1.0, kToleranceLoose);
-  EXPECT_NEAR(x_(1), 1.0, kToleranceLoose);
-  EXPECT_NEAR(x_(2), 1.0, kToleranceLoose);
-  EXPECT_NEAR(x_(3), 1.0, kToleranceLoose);
-  EXPECT_NEAR(x_(4), 1.0, kToleranceLoose);
-  EXPECT_NEAR(x_(5), 1.0, kToleranceLoose);
+  EXPECT_THAT(
+      x_,
+      MatrixPointwise(DoubleNear(kToleranceLoose), Vector::Ones(x_.size())));
 }
 
 // Test if the subspace basis is a valid orthonormal basis of the space spanned
@@ -206,19 +207,17 @@
 
   // Check if the basis is orthonormal.
   const Matrix basis = strategy.subspace_basis();
-  EXPECT_NEAR(basis.col(0).norm(), 1.0, kTolerance);
-  EXPECT_NEAR(basis.col(1).norm(), 1.0, kTolerance);
-  EXPECT_NEAR(basis.col(0).dot(basis.col(1)), 0.0, kTolerance);
+  EXPECT_THAT(basis.transpose() * basis,
+              NormNear(Matrix::Identity(2, 2), kTolerance));
 
   // Check if the gradient projects onto itself.
   const Vector gradient = strategy.gradient();
-  EXPECT_NEAR((gradient - basis * (basis.transpose() * gradient)).norm(),
-              0.0,
-              kTolerance);
+  EXPECT_THAT(gradient,
+              NormNear(basis * (basis.transpose() * gradient), kTolerance));
 
   // Check if the Gauss-Newton point projects onto itself.
   const Vector gn = strategy.gauss_newton_step();
-  EXPECT_NEAR((gn - basis * (basis.transpose() * gn)).norm(), 0.0, kTolerance);
+  EXPECT_THAT(gn, NormNear(basis * (basis.transpose() * gn), kTolerance));
 }
 
 // Test if the step is correct if the gradient and the Gauss-Newton step point
@@ -239,12 +238,9 @@
       strategy.ComputeStep(pso, jacobian_.get(), residual_.data(), x_.data());
 
   EXPECT_NE(summary.termination_type, LinearSolverTerminationType::FAILURE);
-  EXPECT_NEAR(x_(0), 0.0, kToleranceLoose);
-  EXPECT_NEAR(x_(1), 0.0, kToleranceLoose);
-  EXPECT_NEAR(x_(2), options_.initial_radius, kToleranceLoose);
-  EXPECT_NEAR(x_(3), 0.0, kToleranceLoose);
-  EXPECT_NEAR(x_(4), 0.0, kToleranceLoose);
-  EXPECT_NEAR(x_(5), 0.0, kToleranceLoose);
+  Vector expected = Vector::Zero(6);
+  expected(2) = options_.initial_radius;
+  EXPECT_THAT(x_, MatrixPointwise(DoubleNear(kToleranceLoose), expected));
 }
 
 // Test if the step is correct if the gradient and the Gauss-Newton step point
@@ -265,12 +261,8 @@
       strategy.ComputeStep(pso, jacobian_.get(), residual_.data(), x_.data());
 
   EXPECT_NE(summary.termination_type, LinearSolverTerminationType::FAILURE);
-  EXPECT_NEAR(x_(0), 0.0, kToleranceLoose);
-  EXPECT_NEAR(x_(1), 0.0, kToleranceLoose);
-  EXPECT_NEAR(x_(2), 1.0, kToleranceLoose);
-  EXPECT_NEAR(x_(3), 0.0, kToleranceLoose);
-  EXPECT_NEAR(x_(4), 0.0, kToleranceLoose);
-  EXPECT_NEAR(x_(5), 0.0, kToleranceLoose);
+  EXPECT_THAT(x_,
+              MatrixPointwise(DoubleNear(kToleranceLoose), Vector::Unit(6, 2)));
 }
 
 }  // namespace ceres::internal
diff --git a/internal/ceres/dynamic_sparse_normal_cholesky_solver_test.cc b/internal/ceres/dynamic_sparse_normal_cholesky_solver_test.cc
index a54c277..fdfd590 100644
--- a/internal/ceres/dynamic_sparse_normal_cholesky_solver_test.cc
+++ b/internal/ceres/dynamic_sparse_normal_cholesky_solver_test.cc
@@ -39,13 +39,17 @@
 #include "ceres/internal/config.h"
 #include "ceres/linear_least_squares_problems.h"
 #include "ceres/linear_solver.h"
+#include "ceres/test_util.h"
 #include "ceres/triplet_sparse_matrix.h"
 #include "ceres/types.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres {
 namespace internal {
 
+using ::testing::DoubleNear;
+
 // TODO(sameeragarwal): These tests needs to be re-written to be more
 // thorough, they do not really test the dynamic nature of the
 // sparsity.
@@ -86,11 +90,8 @@
 
     EXPECT_EQ(summary.termination_type, LinearSolverTerminationType::SUCCESS);
 
-    for (int i = 0; i < A_->num_cols(); ++i) {
-      EXPECT_NEAR(expected_solution(i), actual_solution(i), 1e-8)
-          << "\nExpected: " << expected_solution.transpose()
-          << "\nActual: " << actual_solution.transpose();
-    }
+    EXPECT_THAT(actual_solution,
+                MatrixPointwise(DoubleNear(1e-8), expected_solution));
   }
 
   void TestSolver(
diff --git a/internal/ceres/householder_vector_test.cc b/internal/ceres/householder_vector_test.cc
index 9f99578..ac3af8d 100644
--- a/internal/ceres/householder_vector_test.cc
+++ b/internal/ceres/householder_vector_test.cc
@@ -31,10 +31,14 @@
 #include "ceres/internal/householder_vector.h"
 
 #include "ceres/eigen.h"
+#include "ceres/test_util.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
 
+using ::testing::DoubleNear;
+
 static void HouseholderTestHelper(const Vector& x) {
   const double kTolerance = 1e-14;
 
@@ -53,9 +57,7 @@
   expected_result(x.rows() - 1) = 1;
   expected_result *= x.norm();
 
-  for (int i = 0; i < x.rows(); ++i) {
-    EXPECT_NEAR(expected_result[i], result[i], kTolerance);
-  }
+  EXPECT_THAT(result, MatrixPointwise(DoubleNear(kTolerance), expected_result));
 }
 
 TEST(HouseholderVector, ZeroPositive) {
diff --git a/internal/ceres/implicit_schur_complement_test.cc b/internal/ceres/implicit_schur_complement_test.cc
index 71fde4d..6cdb083 100644
--- a/internal/ceres/implicit_schur_complement_test.cc
+++ b/internal/ceres/implicit_schur_complement_test.cc
@@ -42,13 +42,14 @@
 #include "ceres/linear_least_squares_problems.h"
 #include "ceres/linear_solver.h"
 #include "ceres/schur_eliminator.h"
+#include "ceres/test_util.h"
 #include "ceres/triplet_sparse_matrix.h"
 #include "ceres/types.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
 
-using testing::AssertionResult;
 
 const double kEpsilon = 1e-14;
 
@@ -57,7 +58,7 @@
   void SetUp() final {
     auto problem = CreateLinearLeastSquaresProblemFromId(2);
 
-    ASSERT_TRUE(problem != nullptr);
+    ASSERT_NE(problem, nullptr);
     A_.reset(down_cast<BlockSparseMatrix*>(problem->A.release()));
     b_ = std::move(problem->b);
     D_ = std::move(problem->D);
@@ -85,7 +86,7 @@
 
     std::unique_ptr<SchurEliminatorBase> eliminator =
         SchurEliminatorBase::Create(options);
-    ASSERT_TRUE(eliminator != nullptr);
+    ASSERT_NE(eliminator, nullptr);
     const bool kFullRankETE = true;
     eliminator->Init(num_eliminate_blocks_, kFullRankETE, bs);
 
@@ -116,7 +117,7 @@
                                solution->data());
   }
 
-  AssertionResult TestImplicitSchurComplement(double* D) {
+  void ExpectImplicitSchurComplementMatchesExplicitOne(double* D) {
     Matrix lhs;
     Vector rhs;
     Vector reference_solution;
@@ -165,12 +166,7 @@
 
       // The i^th column of the implicit schur complement is the same as
       // the explicit schur complement.
-      if ((y - z).norm() > kEpsilon) {
-        return testing::AssertionFailure()
-               << "Explicit and Implicit SchurComplements differ in "
-               << "column " << i << ". explicit: " << y.transpose()
-               << " implicit: " << z.transpose();
-      }
+      EXPECT_THAT(z, NormNear(y, kEpsilon)) << "Schur complement column " << i;
 
       y.setZero();
       y = Z_reference * x;
@@ -178,24 +174,14 @@
       isc.InversePowerSeriesOperatorRightMultiplyAccumulate(x.data(), z.data());
 
       // The i^th column of operator Z stored implicitly is the same as its
-      // explicit version.
-      if ((y - z).norm() > kEpsilon) {
-        return testing::AssertionFailure()
-               << "Explicit and Implicit operators used to approximate the "
-                  "inversion of schur complement via power series expansion "
-                  "differ in column "
-               << i << ". explicit: " << y.transpose()
-               << " implicit: " << z.transpose();
-      }
+      // explicit version used to approximate the inversion of the Schur
+      // complement via power series expansion.
+      EXPECT_THAT(z, NormNear(y, kEpsilon))
+          << "power series operator column " << i;
     }
 
     // Compare the rhs of the reduced linear system
-    if ((isc.rhs() - rhs).norm() > kEpsilon) {
-      return testing::AssertionFailure()
-             << "Explicit and Implicit SchurComplements differ in "
-             << "rhs. explicit: " << rhs.transpose()
-             << " implicit: " << isc.rhs().transpose();
-    }
+    EXPECT_THAT(isc.rhs(), NormNear(rhs, kEpsilon));
 
     // Reference solution to the f_block.
     const Vector reference_f_sol =
@@ -205,14 +191,7 @@
     // reference solution to the f_block.
     Vector sol(num_cols_);
     isc.BackSubstitute(reference_f_sol.data(), sol.data());
-    if ((sol - reference_solution).norm() > kEpsilon) {
-      return testing::AssertionFailure()
-             << "Explicit and Implicit SchurComplements solutions differ. "
-             << "explicit: " << reference_solution.transpose()
-             << " implicit: " << sol.transpose();
-    }
-
-    return testing::AssertionSuccess();
+    EXPECT_THAT(sol, NormNear(reference_solution, kEpsilon));
   }
 
   ContextImpl context_;
@@ -232,8 +211,14 @@
 // We do this with and without regularization to check that the
 // support for the LM diagonal is correct.
 TEST_F(ImplicitSchurComplementTest, SchurMatrixValuesTest) {
-  EXPECT_TRUE(TestImplicitSchurComplement(nullptr));
-  EXPECT_TRUE(TestImplicitSchurComplement(D_.get()));
+  {
+    SCOPED_TRACE("without regularization");
+    ExpectImplicitSchurComplementMatchesExplicitOne(nullptr);
+  }
+  {
+    SCOPED_TRACE("with regularization");
+    ExpectImplicitSchurComplementMatchesExplicitOne(D_.get());
+  }
 }
 
 }  // namespace ceres::internal
diff --git a/internal/ceres/inner_product_computer_test.cc b/internal/ceres/inner_product_computer_test.cc
index b96ff39..65bf3e5 100644
--- a/internal/ceres/inner_product_computer_test.cc
+++ b/internal/ceres/inner_product_computer_test.cc
@@ -33,48 +33,65 @@
 #include <memory>
 #include <numeric>
 #include <random>
+#include <string>
 
 #include "Eigen/SparseCore"
-#include "absl/log/log.h"
+#include "absl/strings/str_format.h"
 #include "ceres/block_sparse_matrix.h"
 #include "ceres/eigen.h"
+#include "ceres/test_util.h"
 #include "ceres/triplet_sparse_matrix.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres {
 namespace internal {
 
-#define COMPUTE_AND_COMPARE                                                   \
-  {                                                                           \
-    inner_product_computer->Compute();                                        \
-    CompressedRowSparseMatrix* actual_product_crsm =                          \
-        inner_product_computer->mutable_result();                             \
-    Matrix actual_inner_product =                                             \
-        Eigen::Map<Eigen::SparseMatrix<double, Eigen::ColMajor>>(             \
-            actual_product_crsm->num_rows(),                                  \
-            actual_product_crsm->num_rows(),                                  \
-            actual_product_crsm->num_nonzeros(),                              \
-            actual_product_crsm->mutable_rows(),                              \
-            actual_product_crsm->mutable_cols(),                              \
-            actual_product_crsm->mutable_values());                           \
-    EXPECT_EQ(actual_inner_product.rows(), actual_inner_product.cols());      \
-    EXPECT_EQ(expected_inner_product.rows(), expected_inner_product.cols());  \
-    EXPECT_EQ(actual_inner_product.rows(), expected_inner_product.rows());    \
-    Matrix expected_t, actual_t;                                              \
-    if (actual_product_crsm->storage_type() ==                                \
-        CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR) {           \
-      expected_t = expected_inner_product.triangularView<Eigen::Upper>();     \
-      actual_t = actual_inner_product.triangularView<Eigen::Upper>();         \
-    } else {                                                                  \
-      expected_t = expected_inner_product.triangularView<Eigen::Lower>();     \
-      actual_t = actual_inner_product.triangularView<Eigen::Lower>();         \
-    }                                                                         \
-    EXPECT_LE((expected_t - actual_t).norm(),                                 \
-              100 * std::numeric_limits<double>::epsilon() * actual_t.norm()) \
-        << "expected: \n"                                                     \
-        << expected_t << "\nactual: \n"                                       \
-        << actual_t;                                                          \
+// Computes the inner product and compares the triangular part it stores to
+// the corresponding part of the expected inner product.
+static void ExpectInnerProduct(InnerProductComputer& inner_product_computer,
+                               const Matrix& expected_inner_product) {
+  inner_product_computer.Compute();
+  CompressedRowSparseMatrix* actual_product_crsm =
+      inner_product_computer.mutable_result();
+  const Matrix actual_inner_product =
+      Eigen::Map<Eigen::SparseMatrix<double, Eigen::ColMajor>>(
+          actual_product_crsm->num_rows(),
+          actual_product_crsm->num_rows(),
+          actual_product_crsm->num_nonzeros(),
+          actual_product_crsm->mutable_rows(),
+          actual_product_crsm->mutable_cols(),
+          actual_product_crsm->mutable_values());
+  ASSERT_EQ(expected_inner_product.rows(), expected_inner_product.cols());
+  Matrix expected_t;
+  Matrix actual_t;
+  if (actual_product_crsm->storage_type() ==
+      CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR) {
+    expected_t = expected_inner_product.triangularView<Eigen::Upper>();
+    actual_t = actual_inner_product.triangularView<Eigen::Upper>();
+  } else {
+    expected_t = expected_inner_product.triangularView<Eigen::Lower>();
+    actual_t = actual_inner_product.triangularView<Eigen::Lower>();
   }
+  EXPECT_THAT(actual_t,
+              RelativeNormNear(expected_t,
+                               100 * std::numeric_limits<double>::epsilon()));
+}
+
+// Describes the options of a random matrix for tracing failures.
+static std::string DescribeRandomMatrixOptions(
+    const BlockSparseMatrix::RandomMatrixOptions& options) {
+  return absl::StrFormat(
+      "num row blocks: %d, num col blocks: %d, row block size: [%d, %d], "
+      "col block size: [%d, %d], block density: %v",
+      options.num_row_blocks,
+      options.num_col_blocks,
+      options.min_row_block_size,
+      options.max_row_block_size,
+      options.min_col_block_size,
+      options.max_col_block_size,
+      options.block_density);
+}
 
 TEST(InnerProductComputer, NormalOperation) {
   const int kMaxNumRowBlocks = 10;
@@ -100,13 +117,7 @@
         options.max_col_block_size = 10;
         options.block_density = distribution(prng);
 
-        VLOG(2) << "num row blocks: " << options.num_row_blocks;
-        VLOG(2) << "num col blocks: " << options.num_col_blocks;
-        VLOG(2) << "min row block size: " << options.min_row_block_size;
-        VLOG(2) << "max row block size: " << options.max_row_block_size;
-        VLOG(2) << "min col block size: " << options.min_col_block_size;
-        VLOG(2) << "max col block size: " << options.max_col_block_size;
-        VLOG(2) << "block density: " << options.block_density;
+        SCOPED_TRACE(DescribeRandomMatrixOptions(options));
 
         std::unique_ptr<BlockSparseMatrix> random_matrix(
             BlockSparseMatrix::CreateRandomMatrix(options, prng));
@@ -130,11 +141,19 @@
         inner_product_computer = InnerProductComputer::Create(
             *random_matrix,
             CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR);
-        COMPUTE_AND_COMPARE;
+
+        {
+          SCOPED_TRACE("lower triangular");
+
+          ExpectInnerProduct(*inner_product_computer, expected_inner_product);
+        }
         inner_product_computer = InnerProductComputer::Create(
             *random_matrix,
             CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR);
-        COMPUTE_AND_COMPARE;
+        {
+          SCOPED_TRACE("upper triangular");
+          ExpectInnerProduct(*inner_product_computer, expected_inner_product);
+        }
       }
     }
   }
@@ -160,13 +179,7 @@
     options.max_col_block_size = 10;
     options.block_density = distribution(prng);
 
-    VLOG(2) << "num row blocks: " << options.num_row_blocks;
-    VLOG(2) << "num col blocks: " << options.num_col_blocks;
-    VLOG(2) << "min row block size: " << options.min_row_block_size;
-    VLOG(2) << "max row block size: " << options.max_row_block_size;
-    VLOG(2) << "min col block size: " << options.min_col_block_size;
-    VLOG(2) << "max col block size: " << options.max_col_block_size;
-    VLOG(2) << "block density: " << options.block_density;
+    SCOPED_TRACE(DescribeRandomMatrixOptions(options));
 
     std::unique_ptr<BlockSparseMatrix> random_matrix(
         BlockSparseMatrix::CreateRandomMatrix(options, prng));
@@ -208,18 +221,23 @@
             start_row_block,
             end_row_block,
             CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR);
-        COMPUTE_AND_COMPARE;
+        {
+          SCOPED_TRACE("lower triangular");
+          ExpectInnerProduct(*inner_product_computer, expected_inner_product);
+        }
         inner_product_computer = InnerProductComputer::Create(
             *random_matrix,
             start_row_block,
             end_row_block,
             CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR);
-        COMPUTE_AND_COMPARE;
+        {
+          SCOPED_TRACE("upper triangular");
+          ExpectInnerProduct(*inner_product_computer, expected_inner_product);
+        }
       }
     }
   }
 }
 
-#undef COMPUTE_AND_COMPARE
 }  // namespace internal
 }  // namespace ceres
diff --git a/internal/ceres/invert_psd_matrix_test.cc b/internal/ceres/invert_psd_matrix_test.cc
index 232e4ea..6c2c0ed 100644
--- a/internal/ceres/invert_psd_matrix_test.cc
+++ b/internal/ceres/invert_psd_matrix_test.cc
@@ -31,6 +31,8 @@
 #include "ceres/invert_psd_matrix.h"
 
 #include "ceres/eigen.h"
+#include "ceres/test_util.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
@@ -53,9 +55,8 @@
 TEST(InvertPSDMatrix, Identity3x3) {
   const Matrix m = Matrix::Identity(3, 3);
   const Matrix inverse_m = InvertPSDMatrix<3>(kFullRank, m);
-  EXPECT_NEAR((inverse_m - m).norm() / m.norm(),
-              0.0,
-              std::numeric_limits<double>::epsilon());
+  EXPECT_THAT(inverse_m,
+              RelativeNormNear(m, std::numeric_limits<double>::epsilon()));
 }
 
 TEST(InvertPSDMatrix, FullRank5x5) {
@@ -64,9 +65,11 @@
   eigenvalues = eigenvalues.array().abs().matrix();
   const Matrix m = RandomPSDMatrixWithEigenValues<5>(eigenvalues);
   const Matrix inverse_m = InvertPSDMatrix<5>(kFullRank, m);
-  EXPECT_NEAR((m * inverse_m - Matrix::Identity(5, 5)).norm() / 5.0,
-              0.0,
-              10 * std::numeric_limits<double>::epsilon());
+  // The tolerance applies to the norm of the difference divided by the
+  // dimension.
+  EXPECT_THAT(m * inverse_m,
+              NormNear(Matrix::Identity(5, 5),
+                       5 * 10 * std::numeric_limits<double>::epsilon()));
 }
 
 TEST(InvertPSDMatrix, RankDeficient5x5) {
@@ -76,11 +79,8 @@
   eigenvalues(3) = 0.0;
   const Matrix m = RandomPSDMatrixWithEigenValues<5>(eigenvalues);
   const Matrix inverse_m = InvertPSDMatrix<5>(kRankDeficient, m);
-  Matrix pseudo_identity = Matrix::Identity(5, 5);
-  pseudo_identity(3, 3) = 0.0;
-  EXPECT_NEAR((m * inverse_m * m - m).norm() / m.norm(),
-              0.0,
-              10 * std::numeric_limits<double>::epsilon());
+  EXPECT_THAT(m * inverse_m * m,
+              RelativeNormNear(m, 10 * std::numeric_limits<double>::epsilon()));
 }
 
 TEST(InvertPSDMatrix, DynamicFullRank5x5) {
@@ -89,9 +89,11 @@
   eigenvalues = eigenvalues.array().abs().matrix();
   const Matrix m = RandomPSDMatrixWithEigenValues<Eigen::Dynamic>(eigenvalues);
   const Matrix inverse_m = InvertPSDMatrix<Eigen::Dynamic>(kFullRank, m);
-  EXPECT_NEAR((m * inverse_m - Matrix::Identity(5, 5)).norm() / 5.0,
-              0.0,
-              10 * std::numeric_limits<double>::epsilon());
+  // The tolerance applies to the norm of the difference divided by the
+  // dimension.
+  EXPECT_THAT(m * inverse_m,
+              NormNear(Matrix::Identity(5, 5),
+                       5 * 10 * std::numeric_limits<double>::epsilon()));
 }
 
 TEST(InvertPSDMatrix, DynamicRankDeficient5x5) {
@@ -101,11 +103,8 @@
   eigenvalues(3) = 0.0;
   const Matrix m = RandomPSDMatrixWithEigenValues<Eigen::Dynamic>(eigenvalues);
   const Matrix inverse_m = InvertPSDMatrix<Eigen::Dynamic>(kRankDeficient, m);
-  Matrix pseudo_identity = Matrix::Identity(5, 5);
-  pseudo_identity(3, 3) = 0.0;
-  EXPECT_NEAR((m * inverse_m * m - m).norm() / m.norm(),
-              0.0,
-              10 * std::numeric_limits<double>::epsilon());
+  EXPECT_THAT(m * inverse_m * m,
+              RelativeNormNear(m, 10 * std::numeric_limits<double>::epsilon()));
 }
 
 }  // namespace ceres::internal
diff --git a/internal/ceres/iterative_refiner_test.cc b/internal/ceres/iterative_refiner_test.cc
index 002626a..c24c7fc 100644
--- a/internal/ceres/iterative_refiner_test.cc
+++ b/internal/ceres/iterative_refiner_test.cc
@@ -39,6 +39,8 @@
 #include "ceres/eigen.h"
 #include "ceres/sparse_cholesky.h"
 #include "ceres/sparse_matrix.h"
+#include "ceres/test_util.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
@@ -177,9 +179,8 @@
   Vector refined_solution(num_cols_);
   refined_solution.setRandom();
   refiner.Refine(lhs, rhs_.data(), &sparse_cholesky, refined_solution.data());
-  EXPECT_NEAR((lhs_ * refined_solution - rhs_).norm(),
-              0.0,
-              std::numeric_limits<double>::epsilon() * 10);
+  EXPECT_THAT(lhs_ * refined_solution,
+              NormNear(rhs_, std::numeric_limits<double>::epsilon() * 10));
 }
 
 TEST_F(SparseIterativeRefinerTest,
@@ -192,9 +193,8 @@
   Vector refined_solution(num_cols_);
   refined_solution.setRandom();
   refiner.Refine(lhs, rhs_.data(), &sparse_cholesky, refined_solution.data());
-  EXPECT_NEAR((lhs_ * refined_solution - rhs_).norm(),
-              0.0,
-              std::numeric_limits<double>::epsilon() * 10);
+  EXPECT_THAT(lhs_ * refined_solution,
+              NormNear(rhs_, std::numeric_limits<double>::epsilon() * 10));
 }
 
 class DenseIterativeRefinerTest : public ::testing::Test {
@@ -230,9 +230,8 @@
                  rhs_.data(),
                  &dense_cholesky,
                  refined_solution.data());
-  EXPECT_NEAR((lhs_ * refined_solution - rhs_).norm(),
-              0.0,
-              std::numeric_limits<double>::epsilon() * 10);
+  EXPECT_THAT(lhs_ * refined_solution,
+              NormNear(rhs_, std::numeric_limits<double>::epsilon() * 10));
 }
 
 TEST_F(DenseIterativeRefinerTest,
@@ -250,9 +249,8 @@
                  rhs_.data(),
                  &dense_cholesky,
                  refined_solution.data());
-  EXPECT_NEAR((lhs_ * refined_solution - rhs_).norm(),
-              0.0,
-              std::numeric_limits<double>::epsilon() * 10);
+  EXPECT_THAT(lhs_ * refined_solution,
+              NormNear(rhs_, std::numeric_limits<double>::epsilon() * 10));
 }
 
 }  // namespace ceres::internal
diff --git a/internal/ceres/iterative_schur_complement_solver_test.cc b/internal/ceres/iterative_schur_complement_solver_test.cc
index 13dfffd..4ef1656 100644
--- a/internal/ceres/iterative_schur_complement_solver_test.cc
+++ b/internal/ceres/iterative_schur_complement_solver_test.cc
@@ -38,6 +38,7 @@
 #include <memory>
 
 #include "Eigen/Dense"
+#include "absl/strings/str_format.h"
 #include "ceres/block_random_access_dense_matrix.h"
 #include "ceres/block_sparse_matrix.h"
 #include "ceres/casts.h"
@@ -46,14 +47,15 @@
 #include "ceres/linear_least_squares_problems.h"
 #include "ceres/linear_solver.h"
 #include "ceres/schur_eliminator.h"
+#include "ceres/test_util.h"
 #include "ceres/triplet_sparse_matrix.h"
 #include "ceres/types.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres {
 namespace internal {
 
-using testing::AssertionResult;
 
 const double kEpsilon = 1e-14;
 
@@ -63,7 +65,7 @@
     std::unique_ptr<LinearLeastSquaresProblem> problem =
         CreateLinearLeastSquaresProblemFromId(problem_id);
 
-    ASSERT_TRUE(problem != nullptr);
+    ASSERT_NE(problem, nullptr);
     A_.reset(down_cast<BlockSparseMatrix*>(problem->A.release()));
     b_ = std::move(problem->b);
     D_ = std::move(problem->D);
@@ -73,9 +75,16 @@
     num_eliminate_blocks_ = problem->num_eliminate_blocks;
   }
 
-  AssertionResult TestSolver(double* D,
-                             PreconditionerType preconditioner_type,
-                             bool use_spse_initialization) {
+  // Expects the iterative Schur complement solver to produce the solution of
+  // the dense QR solver.
+  void ExpectSolutionMatchesDenseQR(double* D,
+                                    PreconditionerType preconditioner_type,
+                                    bool use_spse_initialization) {
+    SCOPED_TRACE(
+        absl::StrFormat("%s regularization, %s, %s SPSE initialization",
+                        D == nullptr ? "without" : "with",
+                        PreconditionerTypeToString(preconditioner_type),
+                        use_spse_initialization ? "with" : "without"));
     TripletSparseMatrix triplet_A(
         A_->num_rows(), A_->num_cols(), A_->num_nonzeros());
     A_->ToTripletSparseMatrix(&triplet_A);
@@ -91,7 +100,11 @@
     LinearSolver::PerSolveOptions per_solve_options;
     per_solve_options.D = D;
     Vector reference_solution(num_cols_);
-    qr->Solve(&dense_A, b_.get(), per_solve_options, reference_solution.data());
+    ASSERT_EQ(
+        qr->Solve(
+              &dense_A, b_.get(), per_solve_options, reference_solution.data())
+            .termination_type,
+        LinearSolverTerminationType::SUCCESS);
 
     options.elimination_groups.push_back(num_eliminate_blocks_);
     options.elimination_groups.push_back(0);
@@ -104,14 +117,7 @@
     Vector isc_sol(num_cols_);
     per_solve_options.r_tolerance = 1e-12;
     isc.Solve(A_.get(), b_.get(), per_solve_options, isc_sol.data());
-    double diff = (isc_sol - reference_solution).norm();
-    if (diff < kEpsilon) {
-      return testing::AssertionSuccess();
-    } else {
-      return testing::AssertionFailure()
-             << "The reference solution differs from the ITERATIVE_SCHUR"
-             << " solution by " << diff << " which is more than " << kEpsilon;
-    }
+    EXPECT_THAT(isc_sol, NormNear(reference_solution, kEpsilon));
   }
 
   int num_rows_;
@@ -124,28 +130,28 @@
 
 TEST_F(IterativeSchurComplementSolverTest, NormalProblemSchurJacobi) {
   SetUpProblem(2);
-  EXPECT_TRUE(TestSolver(nullptr, SCHUR_JACOBI, false));
-  EXPECT_TRUE(TestSolver(D_.get(), SCHUR_JACOBI, false));
+  ExpectSolutionMatchesDenseQR(nullptr, SCHUR_JACOBI, false);
+  ExpectSolutionMatchesDenseQR(D_.get(), SCHUR_JACOBI, false);
 }
 
 TEST_F(IterativeSchurComplementSolverTest,
        NormalProblemSchurJacobiWithPowerSeriesExpansionInitialization) {
   SetUpProblem(2);
-  EXPECT_TRUE(TestSolver(nullptr, SCHUR_JACOBI, true));
-  EXPECT_TRUE(TestSolver(D_.get(), SCHUR_JACOBI, true));
+  ExpectSolutionMatchesDenseQR(nullptr, SCHUR_JACOBI, true);
+  ExpectSolutionMatchesDenseQR(D_.get(), SCHUR_JACOBI, true);
 }
 
 TEST_F(IterativeSchurComplementSolverTest,
        NormalProblemPowerSeriesExpansionPreconditioner) {
   SetUpProblem(5);
-  EXPECT_TRUE(TestSolver(nullptr, SCHUR_POWER_SERIES_EXPANSION, false));
-  EXPECT_TRUE(TestSolver(D_.get(), SCHUR_POWER_SERIES_EXPANSION, false));
+  ExpectSolutionMatchesDenseQR(nullptr, SCHUR_POWER_SERIES_EXPANSION, false);
+  ExpectSolutionMatchesDenseQR(D_.get(), SCHUR_POWER_SERIES_EXPANSION, false);
 }
 
 TEST_F(IterativeSchurComplementSolverTest, ProblemWithNoFBlocks) {
   SetUpProblem(3);
-  EXPECT_TRUE(TestSolver(nullptr, SCHUR_JACOBI, false));
-  EXPECT_TRUE(TestSolver(D_.get(), SCHUR_JACOBI, false));
+  ExpectSolutionMatchesDenseQR(nullptr, SCHUR_JACOBI, false);
+  ExpectSolutionMatchesDenseQR(D_.get(), SCHUR_JACOBI, false);
 }
 
 }  // namespace internal
diff --git a/internal/ceres/levenberg_marquardt_strategy_test.cc b/internal/ceres/levenberg_marquardt_strategy_test.cc
index 5a827b3..14ce186 100644
--- a/internal/ceres/levenberg_marquardt_strategy_test.cc
+++ b/internal/ceres/levenberg_marquardt_strategy_test.cc
@@ -34,6 +34,7 @@
 
 #include "absl/log/check.h"
 #include "absl/log/log.h"
+#include "absl/types/span.h"
 #include "ceres/eigen.h"
 #include "ceres/linear_solver.h"
 #include "ceres/trust_region_strategy.h"
@@ -43,7 +44,9 @@
 using testing::_;
 using testing::AllOf;
 using testing::AnyNumber;
+using testing::DoubleNear;
 using testing::HasSubstr;
+using testing::Pointwise;
 
 namespace ceres {
 namespace internal {
@@ -64,10 +67,9 @@
       const LinearSolver::PerSolveOptions& per_solve_options,
       double* x) final {
     CHECK(per_solve_options.D != nullptr);
-    for (int i = 0; i < num_cols_; ++i) {
-      EXPECT_NEAR(per_solve_options.D[i], diagonal_[i], kTolerance)
-          << i << " " << per_solve_options.D[i] << " " << diagonal_[i];
-    }
+    EXPECT_THAT(absl::MakeConstSpan(per_solve_options.D, num_cols_),
+                Pointwise(DoubleNear(kTolerance),
+                          absl::MakeConstSpan(diagonal_, num_cols_)));
     return {};
   }
 
diff --git a/internal/ceres/partitioned_matrix_view_test.cc b/internal/ceres/partitioned_matrix_view_test.cc
index 50bd46f..67f458e 100644
--- a/internal/ceres/partitioned_matrix_view_test.cc
+++ b/internal/ceres/partitioned_matrix_view_test.cc
@@ -43,11 +43,15 @@
 #include "ceres/eigen.h"
 #include "ceres/linear_least_squares_problems.h"
 #include "ceres/sparse_matrix.h"
+#include "ceres/test_util.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres {
 namespace internal {
 
+using ::testing::DoubleNear;
+
 const double kEpsilon = 1e-14;
 
 // Param = <problem_id, num_threads>
@@ -66,7 +70,7 @@
     const int problem_id = std::get<0>(GetParam());
     const int num_threads = std::get<1>(GetParam());
     auto problem = CreateLinearLeastSquaresProblemFromId(problem_id);
-    ASSERT_TRUE(problem != nullptr);
+    ASSERT_NE(problem, nullptr);
     A_ = std::move(problem->A);
     auto block_sparse = down_cast<BlockSparseMatrix*>(A_.get());
 
@@ -116,9 +120,7 @@
   Vector actual = Vector::Zero(pmv_->num_rows());
   pmv_->RightMultiplyAndAccumulateE(x1.data(), actual.data());
 
-  for (int i = 0; i < pmv_->num_rows(); ++i) {
-    EXPECT_NEAR(actual(i), expected(i), kEpsilon);
-  }
+  EXPECT_THAT(actual, MatrixPointwise(DoubleNear(kEpsilon), expected));
 }
 
 TEST_P(PartitionedMatrixViewTest, RightMultiplyAndAccumulateF) {
@@ -136,9 +138,7 @@
   Vector expected = Vector::Zero(pmv_->num_rows());
   A_->RightMultiplyAndAccumulate(x2.data(), expected.data());
 
-  for (int i = 0; i < pmv_->num_rows(); ++i) {
-    EXPECT_NEAR(actual(i), expected(i), kEpsilon);
-  }
+  EXPECT_THAT(actual, MatrixPointwise(DoubleNear(kEpsilon), expected));
 }
 
 TEST_P(PartitionedMatrixViewTest, LeftMultiplyAndAccumulate) {
@@ -156,12 +156,9 @@
   pmv_->LeftMultiplyAndAccumulateE(x.data(), e_actual.data());
   pmv_->LeftMultiplyAndAccumulateF(x.data(), f_actual.data());
 
-  for (int i = 0; i < pmv_->num_cols(); ++i) {
-    EXPECT_NEAR(expected(i),
-                (i < pmv_->num_cols_e()) ? e_actual(i)
-                                         : f_actual(i - pmv_->num_cols_e()),
-                kEpsilon);
-  }
+  Vector actual(pmv_->num_cols());
+  actual << e_actual, f_actual;
+  EXPECT_THAT(actual, MatrixPointwise(DoubleNear(kEpsilon), expected));
 }
 
 TEST_P(PartitionedMatrixViewTest, BlockDiagonalFtF) {
@@ -184,25 +181,21 @@
   A_->ToDenseMatrix(&EF);
   const auto F = EF.topRightCorner(num_rows, num_cols_f);
 
-  Matrix expected_FtF = F.transpose() * F;
+  const Matrix FtF = F.transpose() * F;
   Matrix actual_FtF;
   block_diagonal_ff->ToDenseMatrix(&actual_FtF);
 
-  // FtF might be not block-diagonal
+  // FtF might be not block-diagonal, but only its diagonal blocks are expected.
+  Matrix expected_FtF = Matrix::Zero(num_cols_f, num_cols_f);
   auto bs = down_cast<BlockSparseMatrix*>(A_.get())->block_structure();
   for (int i = 0; i < num_col_blocks_f; ++i) {
     const auto col_block_f = bs->cols[num_col_blocks_e + i];
     const int block_size = col_block_f.size;
     const int block_pos = col_block_f.position - num_cols_e;
-    const auto cell_expected =
-        expected_FtF.block(block_pos, block_pos, block_size, block_size);
-    auto cell_actual =
-        actual_FtF.block(block_pos, block_pos, block_size, block_size);
-    cell_actual -= cell_expected;
-    EXPECT_NEAR(cell_actual.norm(), 0., kEpsilon);
+    expected_FtF.block(block_pos, block_pos, block_size, block_size) =
+        FtF.block(block_pos, block_pos, block_size, block_size);
   }
-  // There should be nothing remaining outside block-diagonal
-  EXPECT_NEAR(actual_FtF.norm(), 0., kEpsilon);
+  EXPECT_THAT(actual_FtF, NormNear(expected_FtF, kEpsilon));
 }
 
 TEST_P(PartitionedMatrixViewTest, BlockDiagonalEtE) {
@@ -227,7 +220,7 @@
   Matrix actual_EtE;
   block_diagonal_ee->ToDenseMatrix(&actual_EtE);
 
-  EXPECT_NEAR((expected_EtE - actual_EtE).norm(), 0., kEpsilon);
+  EXPECT_THAT(actual_EtE, NormNear(expected_EtE, kEpsilon));
 }
 
 TEST_P(PartitionedMatrixViewTest, UpdateBlockDiagonalEtE) {
@@ -243,7 +236,7 @@
   pmv_single_threaded_->UpdateBlockDiagonalEtE(block_diagonal_ete.get());
   block_diagonal_ete->ToDenseMatrix(&single_threaded);
 
-  EXPECT_NEAR((multi_threaded - single_threaded).norm(), 0., kEpsilon);
+  EXPECT_THAT(multi_threaded, NormNear(single_threaded, kEpsilon));
 }
 
 TEST_P(PartitionedMatrixViewTest, UpdateBlockDiagonalFtF) {
@@ -259,7 +252,7 @@
   pmv_single_threaded_->UpdateBlockDiagonalFtF(block_diagonal_ftf.get());
   block_diagonal_ftf->ToDenseMatrix(&single_threaded);
 
-  EXPECT_NEAR((multi_threaded - single_threaded).norm(), 0., kEpsilon);
+  EXPECT_THAT(multi_threaded, NormNear(single_threaded, kEpsilon));
 }
 
 INSTANTIATE_TEST_SUITE_P(
diff --git a/internal/ceres/power_series_expansion_preconditioner_test.cc b/internal/ceres/power_series_expansion_preconditioner_test.cc
index 1c04162..6737ad2 100644
--- a/internal/ceres/power_series_expansion_preconditioner_test.cc
+++ b/internal/ceres/power_series_expansion_preconditioner_test.cc
@@ -34,10 +34,14 @@
 
 #include "Eigen/Dense"
 #include "ceres/linear_least_squares_problems.h"
+#include "ceres/test_util.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
 
+using ::testing::Not;
+
 const double kEpsilon = 1e-14;
 
 class PowerSeriesExpansionPreconditionerTest : public ::testing::Test {
@@ -96,7 +100,7 @@
 
     y.setZero();
     preconditioner.RightMultiplyAndAccumulate(x.data(), y.data());
-    EXPECT_LT((y - sc_inverse_expected_.col(i)).norm(), kEpsilon)
+    EXPECT_THAT(y, NormNear(sc_inverse_expected_.col(i), kEpsilon))
         << "Reference Schur complement inverse and its estimate via "
            "PowerSeriesExpansionPreconditioner differs in "
         << i
@@ -120,7 +124,7 @@
     y.setZero();
     preconditioner_fixed_n_iterations.RightMultiplyAndAccumulate(x.data(),
                                                                  y.data());
-    EXPECT_LT((y - sc_inverse_expected_.col(i)).norm(), kEpsilon)
+    EXPECT_THAT(y, NormNear(sc_inverse_expected_.col(i), kEpsilon))
         << "Reference Schur complement inverse and its estimate via "
            "PowerSeriesExpansionPreconditioner differs in "
         << i
@@ -143,7 +147,7 @@
 
     y.setZero();
     preconditioner_bad_tolerance.RightMultiplyAndAccumulate(x.data(), y.data());
-    EXPECT_GT((y - sc_inverse_expected_.col(i)).norm(), kEpsilon)
+    EXPECT_THAT(y, Not(NormNear(sc_inverse_expected_.col(i), kEpsilon)))
         << "Reference Schur complement inverse and its estimate via "
            "PowerSeriesExpansionPreconditioner are too similar, tolerance "
            "stopping criteria failed.";
@@ -165,7 +169,7 @@
     y.setZero();
     preconditioner_bad_iterations_limit.RightMultiplyAndAccumulate(x.data(),
                                                                    y.data());
-    EXPECT_GT((y - sc_inverse_expected_.col(i)).norm(), kEpsilon)
+    EXPECT_THAT(y, Not(NormNear(sc_inverse_expected_.col(i), kEpsilon)))
         << "Reference Schur complement inverse and its estimate via "
            "PowerSeriesExpansionPreconditioner are too similar, maximum "
            "iterations stopping criteria failed.";
diff --git a/internal/ceres/schur_eliminator_test.cc b/internal/ceres/schur_eliminator_test.cc
index 476e6af..6c44926 100644
--- a/internal/ceres/schur_eliminator_test.cc
+++ b/internal/ceres/schur_eliminator_test.cc
@@ -47,6 +47,7 @@
 #include "ceres/test_util.h"
 #include "ceres/triplet_sparse_matrix.h"
 #include "ceres/types.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 // TODO(sameeragarwal): Reduce the size of these tests and redo the
@@ -58,7 +59,7 @@
  protected:
   void SetUpFromId(int id) {
     auto problem = CreateLinearLeastSquaresProblemFromId(id);
-    ASSERT_TRUE(problem != nullptr);
+    ASSERT_NE(problem, nullptr);
     SetupHelper(problem.get());
   }
 
@@ -165,15 +166,13 @@
                                reduced_sol.data(),
                                sol.data());
 
-    Matrix delta = (lhs_ref - lhs_expected).selfadjointView<Eigen::Upper>();
-    double diff = delta.norm();
-    EXPECT_NEAR(diff / lhs_expected.norm(), 0.0, relative_tolerance);
-    EXPECT_NEAR((rhs - rhs_expected).norm() / rhs_expected.norm(),
-                0.0,
-                relative_tolerance);
-    EXPECT_NEAR((sol - sol_expected).norm() / sol_expected.norm(),
-                0.0,
-                relative_tolerance);
+    const Matrix symmetric_lhs = lhs_ref.selfadjointView<Eigen::Upper>();
+    EXPECT_THAT(
+        symmetric_lhs,
+        RelativeNormNear(Matrix(lhs_expected.selfadjointView<Eigen::Upper>()),
+                         relative_tolerance));
+    EXPECT_THAT(rhs, RelativeNormNear(rhs_expected, relative_tolerance));
+    EXPECT_THAT(sol, RelativeNormNear(sol_expected, relative_tolerance));
   }
 
   ContextImpl context_;
@@ -348,25 +347,11 @@
   ConstMatrixRef expected_lhsref(
       expected_lhs.values(), actual_lhs.num_cols(), actual_lhs.num_cols());
 
-  EXPECT_NEAR((actual_lhsref - expected_lhsref).norm() / expected_lhsref.norm(),
-              0.0,
-              1e-12)
-      << "expected: \n"
-      << expected_lhsref << "\nactual: \n"
-      << actual_lhsref;
+  EXPECT_THAT(actual_lhsref, RelativeNormNear(expected_lhsref, 1e-12));
 
-  EXPECT_NEAR(
-      (actual_rhs - expected_rhs).norm() / expected_rhs.norm(), 0.0, 1e-12)
-      << "expected: \n"
-      << expected_rhs << "\nactual: \n"
-      << actual_rhs;
+  EXPECT_THAT(actual_rhs, RelativeNormNear(expected_rhs, 1e-12));
 
-  EXPECT_NEAR((actual_e_sol - expected_e_sol).norm() / expected_e_sol.norm(),
-              0.0,
-              1e-12)
-      << "expected: \n"
-      << expected_e_sol << "\nactual: \n"
-      << actual_e_sol;
+  EXPECT_THAT(actual_e_sol, RelativeNormNear(expected_e_sol, 1e-12));
 }
 
 }  // namespace ceres::internal
diff --git a/internal/ceres/small_blas_test.cc b/internal/ceres/small_blas_test.cc
index 3412e84..9a28418 100644
--- a/internal/ceres/small_blas_test.cc
+++ b/internal/ceres/small_blas_test.cc
@@ -34,6 +34,8 @@
 #include <string>
 
 #include "ceres/eigen.h"
+#include "ceres/test_util.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres {
@@ -156,16 +158,12 @@
                                                                  row_stride_c,
                                                                  col_stride_c);
 
-            EXPECT_NEAR((C_plus_ref - C_plus).norm(), 0.0, kTolerance)
+            EXPECT_THAT(C_plus, NormNear(C_plus_ref, kTolerance))
                 << "C += A * B \n"
                 << "row_stride_c : " << row_stride_c << "\n"
                 << "col_stride_c : " << col_stride_c << "\n"
                 << "start_row_c  : " << start_row_c << "\n"
-                << "start_col_c  : " << start_col_c << "\n"
-                << "Cref : \n"
-                << C_plus_ref << "\n"
-                << "C: \n"
-                << C_plus;
+                << "start_col_c  : " << start_col_c;
 
             C_minus_ref.block(start_row_c, start_col_c, kRowA, kColB) -= A * B;
             FunctorTy<kRowA, kColA, kRowB, kColB, -1, kDimType>()(
@@ -181,16 +179,12 @@
                 row_stride_c,
                 col_stride_c);
 
-            EXPECT_NEAR((C_minus_ref - C_minus).norm(), 0.0, kTolerance)
+            EXPECT_THAT(C_minus, NormNear(C_minus_ref, kTolerance))
                 << "C -= A * B \n"
                 << "row_stride_c : " << row_stride_c << "\n"
                 << "col_stride_c : " << col_stride_c << "\n"
                 << "start_row_c  : " << start_row_c << "\n"
-                << "start_col_c  : " << start_col_c << "\n"
-                << "Cref : \n"
-                << C_minus_ref << "\n"
-                << "C: \n"
-                << C_minus;
+                << "start_col_c  : " << start_col_c;
 
             C_assign_ref.block(start_row_c, start_col_c, kRowA, kColB) = A * B;
 
@@ -207,16 +201,12 @@
                 row_stride_c,
                 col_stride_c);
 
-            EXPECT_NEAR((C_assign_ref - C_assign).norm(), 0.0, kTolerance)
+            EXPECT_THAT(C_assign, NormNear(C_assign_ref, kTolerance))
                 << "C = A * B \n"
                 << "row_stride_c : " << row_stride_c << "\n"
                 << "col_stride_c : " << col_stride_c << "\n"
                 << "start_row_c  : " << start_row_c << "\n"
-                << "start_col_c  : " << start_col_c << "\n"
-                << "Cref : \n"
-                << C_assign_ref << "\n"
-                << "C: \n"
-                << C_assign;
+                << "start_col_c  : " << start_col_c;
           }
         }
       }
@@ -269,16 +259,12 @@
                                                                  row_stride_c,
                                                                  col_stride_c);
 
-            EXPECT_NEAR((C_plus_ref - C_plus).norm(), 0.0, kTolerance)
+            EXPECT_THAT(C_plus, NormNear(C_plus_ref, kTolerance))
                 << "C += A' * B \n"
                 << "row_stride_c : " << row_stride_c << "\n"
                 << "col_stride_c : " << col_stride_c << "\n"
                 << "start_row_c  : " << start_row_c << "\n"
-                << "start_col_c  : " << start_col_c << "\n"
-                << "Cref : \n"
-                << C_plus_ref << "\n"
-                << "C: \n"
-                << C_plus;
+                << "start_col_c  : " << start_col_c;
 
             C_minus_ref.block(start_row_c, start_col_c, kColA, kColB) -=
                 A.transpose() * B;
@@ -296,16 +282,12 @@
                 row_stride_c,
                 col_stride_c);
 
-            EXPECT_NEAR((C_minus_ref - C_minus).norm(), 0.0, kTolerance)
+            EXPECT_THAT(C_minus, NormNear(C_minus_ref, kTolerance))
                 << "C -= A' * B \n"
                 << "row_stride_c : " << row_stride_c << "\n"
                 << "col_stride_c : " << col_stride_c << "\n"
                 << "start_row_c  : " << start_row_c << "\n"
-                << "start_col_c  : " << start_col_c << "\n"
-                << "Cref : \n"
-                << C_minus_ref << "\n"
-                << "C: \n"
-                << C_minus;
+                << "start_col_c  : " << start_col_c;
 
             C_assign_ref.block(start_row_c, start_col_c, kColA, kColB) =
                 A.transpose() * B;
@@ -323,16 +305,12 @@
                 row_stride_c,
                 col_stride_c);
 
-            EXPECT_NEAR((C_assign_ref - C_assign).norm(), 0.0, kTolerance)
+            EXPECT_THAT(C_assign, NormNear(C_assign_ref, kTolerance))
                 << "C = A' * B \n"
                 << "row_stride_c : " << row_stride_c << "\n"
                 << "col_stride_c : " << col_stride_c << "\n"
                 << "start_row_c  : " << start_row_c << "\n"
-                << "start_col_c  : " << start_col_c << "\n"
-                << "Cref : \n"
-                << C_assign_ref << "\n"
-                << "C: \n"
-                << C_assign;
+                << "start_col_c  : " << start_col_c;
           }
         }
       }
@@ -534,30 +512,24 @@
           A.data(), num_rows_a, num_cols_a,
           b.data(),
           c_plus.data());
-      EXPECT_NEAR((c_plus_ref - c_plus).norm(), 0.0, kTolerance)
-          << "c += A * b \n"
-          << "c_ref : \n" << c_plus_ref << "\n"
-          << "c: \n" << c_plus;
+      EXPECT_THAT(c_plus, NormNear(c_plus_ref, kTolerance))
+          << "c += A * b \n";
 
       c_minus_ref -= A * b;
       MatrixVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, -1>(
           A.data(), num_rows_a, num_cols_a,
           b.data(),
           c_minus.data());
-      EXPECT_NEAR((c_minus_ref - c_minus).norm(), 0.0, kTolerance)
-          << "c -= A * b \n"
-          << "c_ref : \n" << c_minus_ref << "\n"
-          << "c: \n" << c_minus;
+      EXPECT_THAT(c_minus, NormNear(c_minus_ref, kTolerance))
+          << "c -= A * b \n";
 
       c_assign_ref = A * b;
       MatrixVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 0>(
           A.data(), num_rows_a, num_cols_a,
           b.data(),
           c_assign.data());
-      EXPECT_NEAR((c_assign_ref - c_assign).norm(), 0.0, kTolerance)
-          << "c = A * b \n"
-          << "c_ref : \n" << c_assign_ref << "\n"
-          << "c: \n" << c_assign;
+      EXPECT_THAT(c_assign, NormNear(c_assign_ref, kTolerance))
+          << "c = A * b \n";
       // clang-format on
     }
   }
@@ -589,30 +561,24 @@
           A.data(), num_rows_a, num_cols_a,
           b.data(),
           c_plus.data());
-      EXPECT_NEAR((c_plus_ref - c_plus).norm(), 0.0, kTolerance)
-          << "c += A' * b \n"
-          << "c_ref : \n" << c_plus_ref << "\n"
-          << "c: \n" << c_plus;
+      EXPECT_THAT(c_plus, NormNear(c_plus_ref, kTolerance))
+          << "c += A' * b \n";
 
       c_minus_ref -= A.transpose() * b;
       MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, -1>(
           A.data(), num_rows_a, num_cols_a,
           b.data(),
           c_minus.data());
-      EXPECT_NEAR((c_minus_ref - c_minus).norm(), 0.0, kTolerance)
-          << "c -= A' * b \n"
-          << "c_ref : \n" << c_minus_ref << "\n"
-          << "c: \n" << c_minus;
+      EXPECT_THAT(c_minus, NormNear(c_minus_ref, kTolerance))
+          << "c -= A' * b \n";
 
       c_assign_ref = A.transpose() * b;
       MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 0>(
           A.data(), num_rows_a, num_cols_a,
           b.data(),
           c_assign.data());
-      EXPECT_NEAR((c_assign_ref - c_assign).norm(), 0.0, kTolerance)
-          << "c = A' * b \n"
-          << "c_ref : \n" << c_assign_ref << "\n"
-          << "c: \n" << c_assign;
+      EXPECT_THAT(c_assign, NormNear(c_assign_ref, kTolerance))
+          << "c = A' * b \n";
       // clang-format on
     }
   }
diff --git a/internal/ceres/sparse_normal_cholesky_solver_test.cc b/internal/ceres/sparse_normal_cholesky_solver_test.cc
index f3d6c09..f136430 100644
--- a/internal/ceres/sparse_normal_cholesky_solver_test.cc
+++ b/internal/ceres/sparse_normal_cholesky_solver_test.cc
@@ -37,12 +37,16 @@
 #include "ceres/context_impl.h"
 #include "ceres/linear_least_squares_problems.h"
 #include "ceres/linear_solver.h"
+#include "ceres/test_util.h"
 #include "ceres/triplet_sparse_matrix.h"
 #include "ceres/types.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
 
+using ::testing::DoubleNear;
+
 // TODO(sameeragarwal): These tests needs to be re-written, since
 // SparseNormalCholeskySolver is a composition of two classes now,
 // InnerProductComputer and SparseCholesky.
@@ -56,7 +60,7 @@
     std::unique_ptr<LinearLeastSquaresProblem> problem =
         CreateLinearLeastSquaresProblemFromId(2);
 
-    ASSERT_TRUE(problem != nullptr);
+    ASSERT_NE(problem, nullptr);
     A_.reset(down_cast<BlockSparseMatrix*>(problem->A.release()));
     b_ = std::move(problem->b);
     D_ = std::move(problem->D);
@@ -89,11 +93,8 @@
     EXPECT_EQ(summary.termination_type, LinearSolverTerminationType::SUCCESS);
 
     const double eps = options.use_mixed_precision_solves ? 2e-6 : 1e-8;
-    for (int i = 0; i < A_->num_cols(); ++i) {
-      EXPECT_NEAR(expected_solution(i), actual_solution(i), eps)
-          << "\nExpected: " << expected_solution.transpose()
-          << "\nActual: " << actual_solution.transpose();
-    }
+    EXPECT_THAT(actual_solution,
+                MatrixPointwise(DoubleNear(eps), expected_solution));
   }
 
   void TestSolver(const LinearSolver::Options& options) {
@@ -188,7 +189,7 @@
   ContextImpl context;
   options.context = &context;
   std::string error;
-  CHECK(context.InitCuda(&error)) << error;
+  ASSERT_TRUE(context.InitCuda(&error)) << error;
   TestSolver(options);
 }
 
@@ -200,7 +201,7 @@
   ContextImpl context;
   options.context = &context;
   std::string error;
-  CHECK(context.InitCuda(&error)) << error;
+  ASSERT_TRUE(context.InitCuda(&error)) << error;
   TestSolver(options);
 }
 #endif  // CERES_USE_EIGEN_SPARSE