Deduplicate the sparse matrix test helpers

Sparse matrix comparisons, reference solutions and random matrix setup
are repeated across tests, and mismatching block structures are printed
as raw bytes.

Share the conversion of sparse matrices into dense ones, the dense
reference solution of sparse linear systems and a matcher for compressed
row matrices in the test utilities, print blocks readably and extract
the repeated setup.

Change-Id: Idb2e20cf56598cc72ab38728fbaf85e5b42308c4
diff --git a/internal/ceres/compressed_row_sparse_matrix_test.cc b/internal/ceres/compressed_row_sparse_matrix_test.cc
index 2c1bd15..9e7b587 100644
--- a/internal/ceres/compressed_row_sparse_matrix_test.cc
+++ b/internal/ceres/compressed_row_sparse_matrix_test.cc
@@ -35,46 +35,32 @@
 #include <numeric>
 #include <random>
 #include <string>
-#include <tuple>
 #include <vector>
 
 #include "Eigen/SparseCore"
+#include "absl/strings/str_format.h"
 #include "ceres/casts.h"
 #include "ceres/context_impl.h"
 #include "ceres/crs_matrix.h"
 #include "ceres/eigen.h"
 #include "ceres/linear_least_squares_problems.h"
+#include "ceres/test_util.h"
 #include "ceres/triplet_sparse_matrix.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
 
-static void CompareMatrices(const SparseMatrix* a, const SparseMatrix* b) {
-  EXPECT_EQ(a->num_rows(), b->num_rows());
-  EXPECT_EQ(a->num_cols(), b->num_cols());
-
-  int num_rows = a->num_rows();
-  int num_cols = a->num_cols();
-
-  for (int i = 0; i < num_cols; ++i) {
-    Vector x = Vector::Zero(num_cols);
-    x(i) = 1.0;
-
-    Vector y_a = Vector::Zero(num_rows);
-    Vector y_b = Vector::Zero(num_rows);
-
-    a->RightMultiplyAndAccumulate(x.data(), y_a.data());
-    b->RightMultiplyAndAccumulate(x.data(), y_b.data());
-    EXPECT_EQ((y_a - y_b).norm(), 0);
-  }
-}
+constexpr int kMinNumBlocks = 1;
+constexpr int kMaxNumBlocks = 10;
+constexpr int kNumTrials = 10;
 
 class CompressedRowSparseMatrixTest : public ::testing::Test {
  protected:
   void SetUp() final {
     auto problem = CreateLinearLeastSquaresProblemFromId(1);
 
-    ASSERT_TRUE(problem != nullptr);
+    ASSERT_NE(problem, nullptr);
 
     tsm.reset(down_cast<TripletSparseMatrix*>(problem->A.release()));
     crsm = CompressedRowSparseMatrix::FromTripletSparseMatrix(*tsm);
@@ -109,7 +95,8 @@
 
   tsm->ScaleColumns(scale.data());
   crsm->ScaleColumns(scale.data());
-  CompareMatrices(tsm.get(), crsm.get());
+  EXPECT_THAT(RightMultiplyByIdentity(*crsm),
+              MatrixEq(RightMultiplyByIdentity(*tsm)));
 }
 
 TEST_F(CompressedRowSparseMatrixTest, DeleteRows) {
@@ -120,7 +107,8 @@
   for (int i = 0; i < num_rows; ++i) {
     tsm->Resize(num_rows - i, num_cols);
     crsm->DeleteRows(crsm->num_rows() - tsm->num_rows());
-    CompareMatrices(tsm.get(), crsm.get());
+    EXPECT_THAT(RightMultiplyByIdentity(*crsm),
+                MatrixEq(RightMultiplyByIdentity(*tsm)));
   }
 }
 
@@ -138,7 +126,8 @@
         CompressedRowSparseMatrix::FromTripletSparseMatrix(tsm_appendage);
 
     crsm->AppendRows(*crsm_appendage);
-    CompareMatrices(tsm.get(), crsm.get());
+    EXPECT_THAT(RightMultiplyByIdentity(*crsm),
+                MatrixEq(RightMultiplyByIdentity(*tsm)));
   }
 }
 
@@ -188,7 +177,7 @@
   tsm->ToDenseMatrix(&tsm_dense);
   crsm->ToDenseMatrix(&crsm_dense);
 
-  EXPECT_EQ((tsm_dense - crsm_dense).norm(), 0.0);
+  EXPECT_THAT(tsm_dense, MatrixEq(crsm_dense));
 }
 
 TEST_F(CompressedRowSparseMatrixTest, ToCRSMatrix) {
@@ -196,18 +185,9 @@
   crsm->ToCRSMatrix(&crs_matrix);
   EXPECT_EQ(crsm->num_rows(), crs_matrix.num_rows);
   EXPECT_EQ(crsm->num_cols(), crs_matrix.num_cols);
-  EXPECT_EQ(crsm->num_rows() + 1, crs_matrix.rows.size());
-  EXPECT_EQ(crsm->num_nonzeros(), crs_matrix.cols.size());
-  EXPECT_EQ(crsm->num_nonzeros(), crs_matrix.values.size());
-
-  for (int i = 0; i < crsm->num_rows() + 1; ++i) {
-    EXPECT_EQ(crsm->rows()[i], crs_matrix.rows[i]);
-  }
-
-  for (int i = 0; i < crsm->num_nonzeros(); ++i) {
-    EXPECT_EQ(crsm->cols()[i], crs_matrix.cols[i]);
-    EXPECT_EQ(crsm->values()[i], crs_matrix.values[i]);
-  }
+  EXPECT_THAT(
+      *crsm,
+      CompressedRowsAre(crs_matrix.rows, crs_matrix.cols, crs_matrix.values));
 }
 
 TEST(CompressedRowSparseMatrix, CreateBlockDiagonalMatrix) {
@@ -236,19 +216,15 @@
   x.setOnes();
   y.setZero();
   matrix->RightMultiplyAndAccumulate(x.data(), y.data());
-  for (int i = 0; i < diagonal.size(); ++i) {
-    EXPECT_EQ(y[i], diagonal[i]);
-  }
+  EXPECT_THAT(y, MatrixEq(diagonal));
 
   y.setZero();
   matrix->LeftMultiplyAndAccumulate(x.data(), y.data());
-  for (int i = 0; i < diagonal.size(); ++i) {
-    EXPECT_EQ(y[i], diagonal[i]);
-  }
+  EXPECT_THAT(y, MatrixEq(diagonal));
 
   Matrix dense;
   matrix->ToDenseMatrix(&dense);
-  EXPECT_EQ((dense.diagonal() - diagonal).norm(), 0.0);
+  EXPECT_THAT(dense.diagonal(), MatrixEq(diagonal));
 }
 
 TEST(CompressedRowSparseMatrix, Transpose) {
@@ -307,22 +283,15 @@
 
   auto transpose = matrix.Transpose();
 
-  ASSERT_EQ(transpose->row_blocks().size(), matrix.col_blocks().size());
-  for (int i = 0; i < transpose->row_blocks().size(); ++i) {
-    EXPECT_EQ(transpose->row_blocks()[i], matrix.col_blocks()[i]);
-  }
-
-  ASSERT_EQ(transpose->col_blocks().size(), matrix.row_blocks().size());
-  for (int i = 0; i < transpose->col_blocks().size(); ++i) {
-    EXPECT_EQ(transpose->col_blocks()[i], matrix.row_blocks()[i]);
-  }
+  EXPECT_EQ(transpose->row_blocks(), matrix.col_blocks());
+  EXPECT_EQ(transpose->col_blocks(), matrix.row_blocks());
 
   Matrix dense_matrix;
   matrix.ToDenseMatrix(&dense_matrix);
 
   Matrix dense_transpose;
   transpose->ToDenseMatrix(&dense_transpose);
-  EXPECT_NEAR((dense_matrix - dense_transpose.transpose()).norm(), 0.0, 1e-14);
+  EXPECT_THAT(dense_transpose, NormNear(dense_matrix.transpose(), 1e-14));
 }
 
 TEST(CompressedRowSparseMatrix, FromTripletSparseMatrix) {
@@ -332,8 +301,8 @@
   options.num_cols = 7;
   options.density = 0.5;
 
-  const int kNumTrials = 10;
   for (int i = 0; i < kNumTrials; ++i) {
+    SCOPED_TRACE(absl::StrFormat("trial %d", i));
     auto tsm = TripletSparseMatrix::CreateRandomMatrix(options, prng);
     auto crsm = CompressedRowSparseMatrix::FromTripletSparseMatrix(*tsm);
 
@@ -341,12 +310,9 @@
     tsm->ToDenseMatrix(&expected);
     Matrix actual;
     crsm->ToDenseMatrix(&actual);
-    EXPECT_NEAR((expected - actual).norm() / actual.norm(),
-                0.0,
-                std::numeric_limits<double>::epsilon())
-        << "\nexpected: \n"
-        << expected << "\nactual: \n"
-        << actual;
+    EXPECT_THAT(
+        actual,
+        RelativeNormNear(expected, std::numeric_limits<double>::epsilon()));
   }
 }
 
@@ -357,8 +323,8 @@
   options.num_cols = 7;
   options.density = 0.5;
 
-  const int kNumTrials = 10;
   for (int i = 0; i < kNumTrials; ++i) {
+    SCOPED_TRACE(absl::StrFormat("trial %d", i));
     auto tsm = TripletSparseMatrix::CreateRandomMatrix(options, prng);
     auto crsm =
         CompressedRowSparseMatrix::FromTripletSparseMatrixTransposed(*tsm);
@@ -368,237 +334,152 @@
     Matrix expected = tmp.transpose();
     Matrix actual;
     crsm->ToDenseMatrix(&actual);
-    EXPECT_NEAR((expected - actual).norm() / actual.norm(),
-                0.0,
-                std::numeric_limits<double>::epsilon())
-        << "\nexpected: \n"
-        << expected << "\nactual: \n"
-        << actual;
+    EXPECT_THAT(
+        actual,
+        RelativeNormNear(expected, std::numeric_limits<double>::epsilon()));
   }
 }
 
-using Param = std::tuple<CompressedRowSparseMatrix::StorageType>;
+using StorageType = CompressedRowSparseMatrix::StorageType;
 
-static std::string ParamInfoToString(testing::TestParamInfo<Param> info) {
-  if (std::get<0>(info.param) ==
-      CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
-    return "UPPER";
+static std::string ParamInfoToString(
+    const testing::TestParamInfo<StorageType>& info) {
+  switch (info.param) {
+    case StorageType::UPPER_TRIANGULAR:
+      return "UPPER";
+    case StorageType::LOWER_TRIANGULAR:
+      return "LOWER";
+    case StorageType::UNSYMMETRIC:
+      return "UNSYMMETRIC";
   }
-
-  if (std::get<0>(info.param) ==
-      CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR) {
-    return "LOWER";
-  }
-
-  return "UNSYMMETRIC";
+  return "UNKNOWN";
 }
 
-class RightMultiplyAndAccumulateTest : public ::testing::TestWithParam<Param> {
-};
-
-TEST_P(RightMultiplyAndAccumulateTest, _) {
-  const int kMinNumBlocks = 1;
-  const int kMaxNumBlocks = 10;
-  const int kMinBlockSize = 1;
-  const int kMaxBlockSize = 5;
-  const int kNumTrials = 10;
-  std::mt19937 prng;
+// Creates a random block matrix with twice as many row blocks as column
+// blocks.
+static std::unique_ptr<CompressedRowSparseMatrix> CreateRandomMatrix(
+    int num_blocks, StorageType storage_type, std::mt19937& prng) {
+  constexpr int kMinBlockSize = 1;
+  constexpr int kMaxBlockSize = 5;
   std::uniform_real_distribution<double> uniform(0.5, 1.0);
+  CompressedRowSparseMatrix::RandomMatrixOptions options;
+  options.num_col_blocks = num_blocks;
+  options.min_col_block_size = kMinBlockSize;
+  options.max_col_block_size = kMaxBlockSize;
+  options.num_row_blocks = 2 * num_blocks;
+  options.min_row_block_size = kMinBlockSize;
+  options.max_row_block_size = kMaxBlockSize;
+  options.block_density = uniform(prng);
+  options.storage_type = storage_type;
+  return CompressedRowSparseMatrix::CreateRandomMatrix(options, prng);
+}
+
+// Returns the dense matrix represented by the matrix with the given storage
+// type.
+static Matrix ToFullDenseMatrix(const CompressedRowSparseMatrix& matrix) {
+  Matrix dense;
+  matrix.ToDenseMatrix(&dense);
+  switch (matrix.storage_type()) {
+    case StorageType::UPPER_TRIANGULAR:
+      return dense.selfadjointView<Eigen::Upper>();
+    case StorageType::LOWER_TRIANGULAR:
+      return dense.selfadjointView<Eigen::Lower>();
+    case StorageType::UNSYMMETRIC:
+      return dense;
+  }
+  return dense;
+}
+
+class RightMultiplyAndAccumulateTest
+    : public ::testing::TestWithParam<StorageType> {};
+
+TEST_P(RightMultiplyAndAccumulateTest, MatchesDenseProduct) {
+  constexpr double kTolerance = std::numeric_limits<double>::epsilon() * 10;
+  std::mt19937 prng;
   for (int num_blocks = kMinNumBlocks; num_blocks < kMaxNumBlocks;
        ++num_blocks) {
     for (int trial = 0; trial < kNumTrials; ++trial) {
-      Param param = GetParam();
-      CompressedRowSparseMatrix::RandomMatrixOptions options;
-      options.num_col_blocks = num_blocks;
-      options.min_col_block_size = kMinBlockSize;
-      options.max_col_block_size = kMaxBlockSize;
-      options.num_row_blocks = 2 * num_blocks;
-      options.min_row_block_size = kMinBlockSize;
-      options.max_row_block_size = kMaxBlockSize;
-      options.block_density = uniform(prng);
-      options.storage_type = std::get<0>(param);
-      auto matrix =
-          CompressedRowSparseMatrix::CreateRandomMatrix(options, prng);
-      const int num_rows = matrix->num_rows();
-      const int num_cols = matrix->num_cols();
+      SCOPED_TRACE(absl::StrFormat("%d blocks, trial %d", num_blocks, trial));
+      auto matrix = CreateRandomMatrix(num_blocks, GetParam(), prng);
+      const Vector x = Vector::Random(matrix->num_cols());
 
-      Vector x(num_cols);
-      x.setRandom();
-
-      Vector actual_y(num_rows);
-      actual_y.setZero();
+      Vector actual_y = Vector::Zero(matrix->num_rows());
       matrix->RightMultiplyAndAccumulate(x.data(), actual_y.data());
 
-      Matrix dense;
-      matrix->ToDenseMatrix(&dense);
-      Vector expected_y;
-      if (std::get<0>(param) ==
-          CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
-        expected_y = dense.selfadjointView<Eigen::Upper>() * x;
-      } else if (std::get<0>(param) ==
-                 CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR) {
-        expected_y = dense.selfadjointView<Eigen::Lower>() * x;
-      } else {
-        expected_y = dense * x;
-      }
-
-      ASSERT_NEAR((expected_y - actual_y).norm() / actual_y.norm(),
-                  0.0,
-                  std::numeric_limits<double>::epsilon() * 10)
-          << "\n"
-          << dense << "x:\n"
-          << x.transpose() << "\n"
-          << "expected: \n"
-          << expected_y.transpose() << "\n"
-          << "actual: \n"
-          << actual_y.transpose();
+      const Matrix dense = ToFullDenseMatrix(*matrix);
+      ASSERT_THAT(actual_y, RelativeNormNear(dense * x, kTolerance))
+          << "matrix:\n"
+          << dense << "\nx: " << x.transpose();
     }
   }
 }
 
-INSTANTIATE_TEST_SUITE_P(
-    CompressedRowSparseMatrix,
-    RightMultiplyAndAccumulateTest,
-    ::testing::Values(CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR,
-                      CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR,
-                      CompressedRowSparseMatrix::StorageType::UNSYMMETRIC),
-    ParamInfoToString);
+INSTANTIATE_TEST_SUITE_P(CompressedRowSparseMatrix,
+                         RightMultiplyAndAccumulateTest,
+                         ::testing::Values(StorageType::LOWER_TRIANGULAR,
+                                           StorageType::UPPER_TRIANGULAR,
+                                           StorageType::UNSYMMETRIC),
+                         ParamInfoToString);
 
-class LeftMultiplyAndAccumulateTest : public ::testing::TestWithParam<Param> {};
+class LeftMultiplyAndAccumulateTest
+    : public ::testing::TestWithParam<StorageType> {};
 
-TEST_P(LeftMultiplyAndAccumulateTest, _) {
-  const int kMinNumBlocks = 1;
-  const int kMaxNumBlocks = 10;
-  const int kMinBlockSize = 1;
-  const int kMaxBlockSize = 5;
-  const int kNumTrials = 10;
+TEST_P(LeftMultiplyAndAccumulateTest, MatchesDenseProduct) {
+  constexpr double kTolerance = std::numeric_limits<double>::epsilon() * 10;
   std::mt19937 prng;
-  std::uniform_real_distribution<double> uniform(0.5, 1.0);
   for (int num_blocks = kMinNumBlocks; num_blocks < kMaxNumBlocks;
        ++num_blocks) {
     for (int trial = 0; trial < kNumTrials; ++trial) {
-      Param param = GetParam();
-      CompressedRowSparseMatrix::RandomMatrixOptions options;
-      options.num_col_blocks = num_blocks;
-      options.min_col_block_size = kMinBlockSize;
-      options.max_col_block_size = kMaxBlockSize;
-      options.num_row_blocks = 2 * num_blocks;
-      options.min_row_block_size = kMinBlockSize;
-      options.max_row_block_size = kMaxBlockSize;
-      options.block_density = uniform(prng);
-      options.storage_type = std::get<0>(param);
-      auto matrix =
-          CompressedRowSparseMatrix::CreateRandomMatrix(options, prng);
-      const int num_rows = matrix->num_rows();
-      const int num_cols = matrix->num_cols();
+      SCOPED_TRACE(absl::StrFormat("%d blocks, trial %d", num_blocks, trial));
+      auto matrix = CreateRandomMatrix(num_blocks, GetParam(), prng);
+      const Vector x = Vector::Random(matrix->num_rows());
 
-      Vector x(num_rows);
-      x.setRandom();
-
-      Vector actual_y(num_cols);
-      actual_y.setZero();
+      Vector actual_y = Vector::Zero(matrix->num_cols());
       matrix->LeftMultiplyAndAccumulate(x.data(), actual_y.data());
 
-      Matrix dense;
-      matrix->ToDenseMatrix(&dense);
-      Vector expected_y;
-      if (std::get<0>(param) ==
-          CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
-        expected_y = dense.selfadjointView<Eigen::Upper>() * x;
-      } else if (std::get<0>(param) ==
-                 CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR) {
-        expected_y = dense.selfadjointView<Eigen::Lower>() * x;
-      } else {
-        expected_y = dense.transpose() * x;
-      }
-
-      ASSERT_NEAR((expected_y - actual_y).norm() / actual_y.norm(),
-                  0.0,
-                  std::numeric_limits<double>::epsilon() * 10)
-          << "\n"
-          << dense << "x\n"
-          << x.transpose() << "\n"
-          << "expected: \n"
-          << expected_y.transpose() << "\n"
-          << "actual: \n"
-          << actual_y.transpose();
+      const Matrix dense = ToFullDenseMatrix(*matrix);
+      ASSERT_THAT(actual_y, RelativeNormNear(dense.transpose() * x, kTolerance))
+          << "matrix:\n"
+          << dense << "\nx: " << x.transpose();
     }
   }
 }
 
-INSTANTIATE_TEST_SUITE_P(
-    CompressedRowSparseMatrix,
-    LeftMultiplyAndAccumulateTest,
-    ::testing::Values(CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR,
-                      CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR,
-                      CompressedRowSparseMatrix::StorageType::UNSYMMETRIC),
-    ParamInfoToString);
+INSTANTIATE_TEST_SUITE_P(CompressedRowSparseMatrix,
+                         LeftMultiplyAndAccumulateTest,
+                         ::testing::Values(StorageType::LOWER_TRIANGULAR,
+                                           StorageType::UPPER_TRIANGULAR,
+                                           StorageType::UNSYMMETRIC),
+                         ParamInfoToString);
 
-class SquaredColumnNormTest : public ::testing::TestWithParam<Param> {};
+class SquaredColumnNormTest : public ::testing::TestWithParam<StorageType> {};
 
-TEST_P(SquaredColumnNormTest, _) {
-  const int kMinNumBlocks = 1;
-  const int kMaxNumBlocks = 10;
-  const int kMinBlockSize = 1;
-  const int kMaxBlockSize = 5;
-  const int kNumTrials = 10;
+TEST_P(SquaredColumnNormTest, MatchesDenseSquaredColumnNorm) {
+  constexpr double kTolerance = std::numeric_limits<double>::epsilon() * 10;
   std::mt19937 prng;
-  std::uniform_real_distribution<double> uniform(0.5, 1.0);
   for (int num_blocks = kMinNumBlocks; num_blocks < kMaxNumBlocks;
        ++num_blocks) {
     for (int trial = 0; trial < kNumTrials; ++trial) {
-      Param param = GetParam();
-      CompressedRowSparseMatrix::RandomMatrixOptions options;
-      options.num_col_blocks = num_blocks;
-      options.min_col_block_size = kMinBlockSize;
-      options.max_col_block_size = kMaxBlockSize;
-      options.num_row_blocks = 2 * num_blocks;
-      options.min_row_block_size = kMinBlockSize;
-      options.max_row_block_size = kMaxBlockSize;
-      options.block_density = uniform(prng);
-      options.storage_type = std::get<0>(param);
-      auto matrix =
-          CompressedRowSparseMatrix::CreateRandomMatrix(options, prng);
-      const int num_cols = matrix->num_cols();
+      SCOPED_TRACE(absl::StrFormat("%d blocks, trial %d", num_blocks, trial));
+      auto matrix = CreateRandomMatrix(num_blocks, GetParam(), prng);
 
-      Vector actual(num_cols);
-      actual.setZero();
+      Vector actual = Vector::Zero(matrix->num_cols());
       matrix->SquaredColumnNorm(actual.data());
 
-      Matrix dense;
-      matrix->ToDenseMatrix(&dense);
-      Vector expected;
-      if (std::get<0>(param) ==
-          CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
-        const Matrix full = dense.selfadjointView<Eigen::Upper>();
-        expected = full.colwise().squaredNorm();
-      } else if (std::get<0>(param) ==
-                 CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR) {
-        const Matrix full = dense.selfadjointView<Eigen::Lower>();
-        expected = full.colwise().squaredNorm();
-      } else {
-        expected = dense.colwise().squaredNorm();
-      }
-
-      ASSERT_NEAR((expected - actual).norm() / actual.norm(),
-                  0.0,
-                  std::numeric_limits<double>::epsilon() * 10)
-          << "\n"
-          << dense << "expected: \n"
-          << expected.transpose() << "\n"
-          << "actual: \n"
-          << actual.transpose();
+      const Matrix dense = ToFullDenseMatrix(*matrix);
+      const Vector expected = dense.colwise().squaredNorm();
+      ASSERT_THAT(actual, RelativeNormNear(expected, kTolerance)) << "matrix:\n"
+                                                                  << dense;
     }
   }
 }
 
-INSTANTIATE_TEST_SUITE_P(
-    CompressedRowSparseMatrix,
-    SquaredColumnNormTest,
-    ::testing::Values(CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR,
-                      CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR,
-                      CompressedRowSparseMatrix::StorageType::UNSYMMETRIC),
-    ParamInfoToString);
+INSTANTIATE_TEST_SUITE_P(CompressedRowSparseMatrix,
+                         SquaredColumnNormTest,
+                         ::testing::Values(StorageType::LOWER_TRIANGULAR,
+                                           StorageType::UPPER_TRIANGULAR,
+                                           StorageType::UNSYMMETRIC),
+                         ParamInfoToString);
 
 const int kMaxNumThreads = 8;
 class CompressedRowSparseMatrixParallelTest
@@ -611,54 +492,26 @@
 
 TEST_P(CompressedRowSparseMatrixParallelTest,
        RightMultiplyAndAccumulateUnsymmetric) {
-  const int kMinNumBlocks = 1;
-  const int kMaxNumBlocks = 10;
-  const int kMinBlockSize = 1;
-  const int kMaxBlockSize = 5;
-  const int kNumTrials = 10;
+  constexpr double kTolerance = std::numeric_limits<double>::epsilon() * 10;
   const int kNumThreads = GetParam();
   std::mt19937 prng;
-  std::uniform_real_distribution<double> uniform(0.5, 1.0);
   for (int num_blocks = kMinNumBlocks; num_blocks < kMaxNumBlocks;
        ++num_blocks) {
     for (int trial = 0; trial < kNumTrials; ++trial) {
-      CompressedRowSparseMatrix::RandomMatrixOptions options;
-      options.num_col_blocks = num_blocks;
-      options.min_col_block_size = kMinBlockSize;
-      options.max_col_block_size = kMaxBlockSize;
-      options.num_row_blocks = 2 * num_blocks;
-      options.min_row_block_size = kMinBlockSize;
-      options.max_row_block_size = kMaxBlockSize;
-      options.block_density = uniform(prng);
-      options.storage_type =
-          CompressedRowSparseMatrix::StorageType::UNSYMMETRIC;
+      SCOPED_TRACE(absl::StrFormat("%d blocks, trial %d", num_blocks, trial));
       auto matrix =
-          CompressedRowSparseMatrix::CreateRandomMatrix(options, prng);
-      const int num_rows = matrix->num_rows();
-      const int num_cols = matrix->num_cols();
+          CreateRandomMatrix(num_blocks, StorageType::UNSYMMETRIC, prng);
+      const Vector x = Vector::Random(matrix->num_cols());
 
-      Vector x(num_cols);
-      x.setRandom();
-
-      Vector actual_y(num_rows);
-      actual_y.setZero();
+      Vector actual_y = Vector::Zero(matrix->num_rows());
       matrix->RightMultiplyAndAccumulate(
           x.data(), actual_y.data(), &context_, kNumThreads);
 
       Matrix dense;
       matrix->ToDenseMatrix(&dense);
-      Vector expected_y = dense * x;
-
-      ASSERT_NEAR((expected_y - actual_y).norm() / actual_y.norm(),
-                  0.0,
-                  std::numeric_limits<double>::epsilon() * 10)
-          << "\n"
-          << dense << "x:\n"
-          << x.transpose() << "\n"
-          << "expected: \n"
-          << expected_y.transpose() << "\n"
-          << "actual: \n"
-          << actual_y.transpose();
+      ASSERT_THAT(actual_y, RelativeNormNear(dense * x, kTolerance))
+          << "matrix:\n"
+          << dense << "\nx: " << x.transpose();
     }
   }
 }
diff --git a/internal/ceres/dense_sparse_matrix_test.cc b/internal/ceres/dense_sparse_matrix_test.cc
index 67f6f33..7e9dca5 100644
--- a/internal/ceres/dense_sparse_matrix_test.cc
+++ b/internal/ceres/dense_sparse_matrix_test.cc
@@ -39,39 +39,20 @@
 #include "ceres/casts.h"
 #include "ceres/eigen.h"
 #include "ceres/linear_least_squares_problems.h"
+#include "ceres/test_util.h"
 #include "ceres/triplet_sparse_matrix.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
 
-static void CompareMatrices(const SparseMatrix* a, const SparseMatrix* b) {
-  EXPECT_EQ(a->num_rows(), b->num_rows());
-  EXPECT_EQ(a->num_cols(), b->num_cols());
-
-  int num_rows = a->num_rows();
-  int num_cols = a->num_cols();
-
-  for (int i = 0; i < num_cols; ++i) {
-    Vector x = Vector::Zero(num_cols);
-    x(i) = 1.0;
-
-    Vector y_a = Vector::Zero(num_rows);
-    Vector y_b = Vector::Zero(num_rows);
-
-    a->RightMultiplyAndAccumulate(x.data(), y_a.data());
-    b->RightMultiplyAndAccumulate(x.data(), y_b.data());
-
-    EXPECT_EQ((y_a - y_b).norm(), 0);
-  }
-}
-
 class DenseSparseMatrixTest : public ::testing::Test {
  protected:
   void SetUp() final {
     std::unique_ptr<LinearLeastSquaresProblem> problem =
         CreateLinearLeastSquaresProblemFromId(1);
 
-    ASSERT_TRUE(problem != nullptr);
+    ASSERT_NE(problem, nullptr);
 
     tsm.reset(down_cast<TripletSparseMatrix*>(problem->A.release()));
     dsm = std::make_unique<DenseSparseMatrix>(*tsm);
@@ -88,7 +69,8 @@
 };
 
 TEST_F(DenseSparseMatrixTest, RightMultiplyAndAccumulate) {
-  CompareMatrices(tsm.get(), dsm.get());
+  EXPECT_THAT(RightMultiplyByIdentity(*dsm),
+              MatrixEq(RightMultiplyByIdentity(*tsm)));
 
   // Try with a not entirely zero vector to verify column interactions, which
   // could be masked by a subtle bug when using the elementary vectors.
@@ -102,7 +84,7 @@
   tsm->RightMultiplyAndAccumulate(a.data(), b1.data());
   dsm->RightMultiplyAndAccumulate(a.data(), b2.data());
 
-  EXPECT_EQ((b1 - b2).norm(), 0);
+  EXPECT_THAT(b1, MatrixEq(b2));
 }
 
 TEST_F(DenseSparseMatrixTest, LeftMultiplyAndAccumulate) {
@@ -116,7 +98,7 @@
     tsm->LeftMultiplyAndAccumulate(a.data(), b1.data());
     dsm->LeftMultiplyAndAccumulate(a.data(), b2.data());
 
-    EXPECT_EQ((b1 - b2).norm(), 0);
+    EXPECT_THAT(b1, MatrixEq(b2));
   }
 
   // Try with a not entirely zero vector to verify column interactions, which
@@ -131,7 +113,7 @@
   tsm->LeftMultiplyAndAccumulate(a.data(), b1.data());
   dsm->LeftMultiplyAndAccumulate(a.data(), b2.data());
 
-  EXPECT_EQ((b1 - b2).norm(), 0);
+  EXPECT_THAT(b1, MatrixEq(b2));
 }
 
 TEST_F(DenseSparseMatrixTest, ColumnNorm) {
@@ -141,7 +123,7 @@
   tsm->SquaredColumnNorm(b1.data());
   dsm->SquaredColumnNorm(b2.data());
 
-  EXPECT_EQ((b1 - b2).norm(), 0);
+  EXPECT_THAT(b1, MatrixEq(b2));
 }
 
 TEST_F(DenseSparseMatrixTest, Scale) {
@@ -151,7 +133,8 @@
   }
   tsm->ScaleColumns(scale.data());
   dsm->ScaleColumns(scale.data());
-  CompareMatrices(tsm.get(), dsm.get());
+  EXPECT_THAT(RightMultiplyByIdentity(*dsm),
+              MatrixEq(RightMultiplyByIdentity(*tsm)));
 }
 
 TEST_F(DenseSparseMatrixTest, ToDenseMatrix) {
@@ -161,7 +144,7 @@
   tsm->ToDenseMatrix(&tsm_dense);
   dsm->ToDenseMatrix(&dsm_dense);
 
-  EXPECT_EQ((tsm_dense - dsm_dense).norm(), 0.0);
+  EXPECT_THAT(tsm_dense, MatrixEq(dsm_dense));
 }
 
 }  // namespace ceres::internal
diff --git a/internal/ceres/sparse_cholesky_test.cc b/internal/ceres/sparse_cholesky_test.cc
index 1749128..429ed17 100644
--- a/internal/ceres/sparse_cholesky_test.cc
+++ b/internal/ceres/sparse_cholesky_test.cc
@@ -51,6 +51,7 @@
 #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"
@@ -85,33 +86,6 @@
   return random_matrix;
 }
 
-bool ComputeExpectedSolution(const CompressedRowSparseMatrix& lhs,
-                             const Vector& rhs,
-                             Vector* solution) {
-  Matrix eigen_lhs;
-  lhs.ToDenseMatrix(&eigen_lhs);
-  if (lhs.storage_type() ==
-      CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
-    Matrix full_lhs = eigen_lhs.selfadjointView<Eigen::Upper>();
-    Eigen::LLT<Matrix, Eigen::Upper> llt =
-        eigen_lhs.selfadjointView<Eigen::Upper>().llt();
-    if (llt.info() != Eigen::Success) {
-      return false;
-    }
-    *solution = llt.solve(rhs);
-    return (llt.info() == Eigen::Success);
-  }
-
-  Matrix full_lhs = eigen_lhs.selfadjointView<Eigen::Lower>();
-  Eigen::LLT<Matrix, Eigen::Lower> llt =
-      eigen_lhs.selfadjointView<Eigen::Lower>().llt();
-  if (llt.info() != Eigen::Success) {
-    return false;
-  }
-  *solution = llt.solve(rhs);
-  return (llt.info() == Eigen::Success);
-}
-
 void SparseCholeskySolverUnitTest(
     const SparseLinearAlgebraLibraryType sparse_linear_algebra_library_type,
     const bool use_single_precision,
@@ -127,7 +101,7 @@
   ContextImpl context;
   sparse_cholesky_options.context = &context;
   std::string error;
-  CHECK(context.InitCuda(&error)) << error;
+  ASSERT_TRUE(context.InitCuda(&error)) << error;
 #endif  // CERES_NO_CUDSS
 
   sparse_cholesky_options.sparse_linear_algebra_library_type =
@@ -155,11 +129,12 @@
   Vector expected(lhs->num_rows());
   Vector actual(lhs->num_rows());
 
-  EXPECT_TRUE(ComputeExpectedSolution(*lhs, rhs, &expected));
+  ASSERT_TRUE(SolveUsingDenseCholesky(*lhs, rhs, &expected));
   std::string message;
-  EXPECT_EQ(
+  ASSERT_EQ(
       sparse_cholesky->FactorAndSolve(lhs, rhs.data(), actual.data(), &message),
-      LinearSolverTerminationType::SUCCESS);
+      LinearSolverTerminationType::SUCCESS)
+      << message;
   Matrix eigen_lhs;
   lhs->ToDenseMatrix(&eigen_lhs);
   const double kTolerance =
@@ -167,9 +142,8 @@
                             : std::numeric_limits<double>::epsilon()) *
       20;
 
-  EXPECT_NEAR((actual - expected).norm() / actual.norm(), 0.0, kTolerance)
-      << "\n"
-      << eigen_lhs;
+  EXPECT_THAT(actual, RelativeNormNear(expected, kTolerance)) << "lhs:\n"
+                                                              << eigen_lhs;
 }
 
 // SparseLinearAlgebraLibraryType
@@ -184,8 +158,7 @@
   std::stringstream ss;
   ss << SparseLinearAlgebraLibraryTypeToString(std::get<0>(param)) << "_"
      << (std::get<1>(param) ? "FLOAT" : "DOUBLE") << "_" << std::get<2>(param)
-     << "_"
-     << (std::get<3>(param) ? "UseBlockStructure" : "NoBlockStructure");
+     << "_" << (std::get<3>(param) ? "UseBlockStructure" : "NoBlockStructure");
   return ss.str();
 }
 
diff --git a/internal/ceres/subset_preconditioner_test.cc b/internal/ceres/subset_preconditioner_test.cc
index 016a845..55a2da4 100644
--- a/internal/ceres/subset_preconditioner_test.cc
+++ b/internal/ceres/subset_preconditioner_test.cc
@@ -41,42 +41,14 @@
 #include "ceres/eigen.h"
 #include "ceres/inner_product_computer.h"
 #include "ceres/internal/config.h"
+#include "ceres/test_util.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace ceres::internal {
 
 namespace {
 
-// TODO(sameeragarwal): Refactor the following two functions out of
-// here and sparse_cholesky_test.cc into a more suitable place.
-template <int UpLoType>
-bool SolveLinearSystemUsingEigen(const Matrix& lhs,
-                                 const Vector rhs,
-                                 Vector* solution) {
-  Eigen::LLT<Matrix, UpLoType> llt = lhs.selfadjointView<UpLoType>().llt();
-  if (llt.info() != Eigen::Success) {
-    return false;
-  }
-  *solution = llt.solve(rhs);
-  return (llt.info() == Eigen::Success);
-}
-
-// Use Eigen's Dense Cholesky solver to compute the solution to a
-// sparse linear system.
-bool ComputeExpectedSolution(const CompressedRowSparseMatrix& lhs,
-                             const Vector& rhs,
-                             Vector* solution) {
-  Matrix dense_triangular_lhs;
-  lhs.ToDenseMatrix(&dense_triangular_lhs);
-  if (lhs.storage_type() ==
-      CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
-    Matrix full_lhs = dense_triangular_lhs.selfadjointView<Eigen::Upper>();
-    return SolveLinearSystemUsingEigen<Eigen::Upper>(full_lhs, rhs, solution);
-  }
-  return SolveLinearSystemUsingEigen<Eigen::Lower>(
-      dense_triangular_lhs, rhs, solution);
-}
-
 using Param = std::tuple<SparseLinearAlgebraLibraryType, bool>;
 
 std::string ParamInfoToString(testing::TestParamInfo<Param> info) {
@@ -158,20 +130,18 @@
     CompressedRowSparseMatrix* lhs = inner_product_computer_->mutable_result();
     Vector rhs = Vector::Random(lhs->num_rows());
     Vector expected(lhs->num_rows());
-    EXPECT_TRUE(ComputeExpectedSolution(*lhs, rhs, &expected));
+    ASSERT_TRUE(SolveUsingDenseCholesky(*lhs, rhs, &expected));
 
     Vector actual(lhs->num_rows());
     preconditioner_->RightMultiplyAndAccumulate(rhs.data(), actual.data());
 
     Matrix eigen_lhs;
     lhs->ToDenseMatrix(&eigen_lhs);
-    EXPECT_NEAR((actual - expected).norm() / actual.norm(),
-                0.0,
-                std::numeric_limits<double>::epsilon() * 10)
-        << "\n"
-        << eigen_lhs << "\n"
-        << expected.transpose() << "\n"
-        << actual.transpose();
+    EXPECT_THAT(
+        actual,
+        RelativeNormNear(expected, std::numeric_limits<double>::epsilon() * 10))
+        << "lhs:\n"
+        << eigen_lhs;
   }
 }
 
diff --git a/internal/ceres/test_util.cc b/internal/ceres/test_util.cc
index 1b14202..0416b93 100644
--- a/internal/ceres/test_util.cc
+++ b/internal/ceres/test_util.cc
@@ -43,6 +43,7 @@
 #include <tuple>
 #include <utility>
 
+#include "Eigen/Cholesky"
 #include "absl/log/check.h"
 #include "absl/log/log.h"
 #include "absl/strings/str_format.h"
@@ -330,6 +331,35 @@
   tuple_matcher_.DescribeNegationTo(os);
 }
 
+Matrix RightMultiplyByIdentity(const SparseMatrix& m) {
+  Matrix dense(m.num_rows(), m.num_cols());
+  for (int i = 0; i < m.num_cols(); ++i) {
+    const Vector x = Vector::Unit(m.num_cols(), i);
+    Vector y = Vector::Zero(m.num_rows());
+    m.RightMultiplyAndAccumulate(x.data(), y.data());
+    dense.col(i) = y;
+  }
+  return dense;
+}
+
+bool SolveUsingDenseCholesky(const CompressedRowSparseMatrix& lhs,
+                             const Vector& rhs,
+                             Vector* solution) {
+  Matrix dense_triangular_lhs;
+  lhs.ToDenseMatrix(&dense_triangular_lhs);
+  const Matrix dense_lhs =
+      lhs.storage_type() ==
+              CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR
+          ? Matrix(dense_triangular_lhs.selfadjointView<Eigen::Upper>())
+          : Matrix(dense_triangular_lhs.selfadjointView<Eigen::Lower>());
+  const Eigen::LLT<Matrix> llt(dense_lhs);
+  if (llt.info() != Eigen::Success) {
+    return false;
+  }
+  *solution = llt.solve(rhs);
+  return llt.info() == Eigen::Success;
+}
+
 std::string TestFileAbsolutePath(const std::string& filename) {
 #ifdef CERES_TEST_DATA_DIR
   // The absolute data directory does not depend on the location of the
diff --git a/internal/ceres/test_util.h b/internal/ceres/test_util.h
index ee21d5d..9ccebf9 100644
--- a/internal/ceres/test_util.h
+++ b/internal/ceres/test_util.h
@@ -42,12 +42,16 @@
 
 #include "absl/log/check.h"
 #include "absl/strings/str_format.h"
+#include "absl/types/span.h"
+#include "ceres/block_structure.h"
+#include "ceres/compressed_row_sparse_matrix.h"
 #include "ceres/eigen.h"
 #include "ceres/internal/disable_warnings.h"
 #include "ceres/internal/export.h"
 #include "ceres/jet.h"
 #include "ceres/problem.h"
 #include "ceres/solver.h"
+#include "ceres/sparse_matrix.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
@@ -361,6 +365,51 @@
                        MatrixPointwise(RelativelyNear(tolerance), expected.v)));
 }
 
+// Returns the dense matrix whose columns are the products of m and the
+// columns of the identity matrix computed by RightMultiplyAndAccumulate.
+CERES_NO_EXPORT Matrix RightMultiplyByIdentity(const SparseMatrix& m);
+
+// Solves the linear system whose symmetric matrix is given by the triangular
+// part stored in lhs using a dense Cholesky factorization. Returns false if
+// the factorization fails.
+CERES_NO_EXPORT bool SolveUsingDenseCholesky(
+    const CompressedRowSparseMatrix& lhs, const Vector& rhs, Vector* solution);
+
+// Prints a Block in assertion failure messages.
+inline void PrintTo(const Block& block, std::ostream* os) {
+  *os << absl::StrFormat(
+      "Block(size=%d, position=%d)", block.size, block.position);
+}
+
+// Matches a CompressedRowSparseMatrix whose row offsets, column indices and
+// values are equal to the given containers.
+template <typename Rows, typename Cols, typename Values>
+auto CompressedRowsAre(const Rows& rows,
+                       const Cols& cols,
+                       const Values& values) {
+  using ::testing::ElementsAreArray;
+  using ::testing::ResultOf;
+  return ::testing::AllOf(
+      ResultOf(
+          "row offsets",
+          [](const CompressedRowSparseMatrix& m) {
+            return absl::MakeConstSpan(m.rows(), m.num_rows() + 1);
+          },
+          ElementsAreArray(rows)),
+      ResultOf(
+          "column indices",
+          [](const CompressedRowSparseMatrix& m) {
+            return absl::MakeConstSpan(m.cols(), m.num_nonzeros());
+          },
+          ElementsAreArray(cols)),
+      ResultOf(
+          "values",
+          [](const CompressedRowSparseMatrix& m) {
+            return absl::MakeConstSpan(m.values(), m.num_nonzeros());
+          },
+          ElementsAreArray(values)));
+}
+
 // Construct a fully qualified path for the test file depending on the
 // local build/testing environment.
 CERES_NO_EXPORT std::string TestFileAbsolutePath(const std::string& filename);
diff --git a/internal/ceres/test_util_test.cc b/internal/ceres/test_util_test.cc
index f5eac0f..32107b7 100644
--- a/internal/ceres/test_util_test.cc
+++ b/internal/ceres/test_util_test.cc
@@ -28,15 +28,21 @@
 
 #include "ceres/test_util.h"
 
+#include <algorithm>
 #include <cfenv>
+#include <iterator>
 #include <limits>
+#include <memory>
 #include <string>
 #include <tuple>
 #include <type_traits>
 #include <vector>
 
+#include "ceres/block_structure.h"
+#include "ceres/compressed_row_sparse_matrix.h"
 #include "ceres/eigen.h"
 #include "ceres/jet.h"
+#include "ceres/triplet_sparse_matrix.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
@@ -459,5 +465,108 @@
   EXPECT_DOUBLE_EQ(2.0 * kHalfSqrt2 * kHalfSqrt2, 1.0);
 }
 
+TEST(RightMultiplyByIdentity, ReconstructsTheDenseMatrix) {
+  TripletSparseMatrix m(2, 3, 2);
+  m.mutable_rows()[0] = 0;
+  m.mutable_cols()[0] = 2;
+  m.mutable_values()[0] = 4.0;
+  m.mutable_rows()[1] = 1;
+  m.mutable_cols()[1] = 0;
+  m.mutable_values()[1] = 5.0;
+  m.set_num_nonzeros(2);
+
+  Matrix expected(2, 3);
+  expected << 0.0, 0.0, 4.0, 5.0, 0.0, 0.0;
+  EXPECT_THAT(RightMultiplyByIdentity(m), MatrixEq(expected));
+}
+
+// Creates the symmetric positive definite matrix
+//
+//   [ 4 2 ]
+//   [ 2 3 ]
+//
+// storing only the given triangular part.
+std::unique_ptr<CompressedRowSparseMatrix> CreateSymmetricMatrix(
+    CompressedRowSparseMatrix::StorageType storage_type) {
+  auto m = std::make_unique<CompressedRowSparseMatrix>(2, 2, 3);
+  m->set_storage_type(storage_type);
+  const bool upper =
+      storage_type == CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR;
+  const int rows[] = {0, upper ? 2 : 1, 3};
+  const int upper_cols[] = {0, 1, 1};
+  const int lower_cols[] = {0, 0, 1};
+  const double values[] = {4.0, 2.0, 3.0};
+  std::copy(std::begin(rows), std::end(rows), m->mutable_rows());
+  std::copy(std::begin(upper ? upper_cols : lower_cols),
+            std::end(upper ? upper_cols : lower_cols),
+            m->mutable_cols());
+  std::copy(std::begin(values), std::end(values), m->mutable_values());
+  return m;
+}
+
+TEST(SolveUsingDenseCholesky, SolvesSystemsStoredInEitherTriangle) {
+  const Eigen::Vector2d expected(1.0, -2.0);
+  const Eigen::Vector2d rhs(4.0 * 1.0 + 2.0 * -2.0, 2.0 * 1.0 + 3.0 * -2.0);
+  for (const auto storage_type :
+       {CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR,
+        CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR}) {
+    const auto lhs = CreateSymmetricMatrix(storage_type);
+    Vector solution;
+    ASSERT_TRUE(SolveUsingDenseCholesky(*lhs, rhs, &solution));
+    EXPECT_THAT(solution, NormNear(expected, kTolerance));
+  }
+}
+
+TEST(SolveUsingDenseCholesky, FailsForIndefiniteMatrices) {
+  auto lhs = CreateSymmetricMatrix(
+      CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR);
+  lhs->mutable_values()[0] = -4.0;
+  Vector solution;
+  EXPECT_FALSE(SolveUsingDenseCholesky(*lhs, Vector::Ones(2), &solution));
+}
+
+TEST(PrintTo, PrintsTheSizeAndThePositionOfABlock) {
+  EXPECT_EQ(::testing::PrintToString(Block(2, 3)), "Block(size=2, position=3)");
+}
+
+// Creates the matrix
+//
+//   [ 1 0 2 ]
+//   [ 0 3 0 ]
+std::unique_ptr<CompressedRowSparseMatrix> CreateCompressedRowSparseMatrix() {
+  auto m = std::make_unique<CompressedRowSparseMatrix>(2, 3, 3);
+  const int rows[] = {0, 2, 3};
+  const int cols[] = {0, 2, 1};
+  const double values[] = {1.0, 2.0, 3.0};
+  std::copy(std::begin(rows), std::end(rows), m->mutable_rows());
+  std::copy(std::begin(cols), std::end(cols), m->mutable_cols());
+  std::copy(std::begin(values), std::end(values), m->mutable_values());
+  return m;
+}
+
+TEST(CompressedRowsAre, MatchesTheCompressedRowArrays) {
+  const auto m = CreateCompressedRowSparseMatrix();
+  EXPECT_THAT(*m,
+              CompressedRowsAre(std::vector{0, 2, 3},
+                                std::vector{0, 2, 1},
+                                std::vector{1.0, 2.0, 3.0}));
+}
+
+TEST(CompressedRowsAre, ExplainsMismatchingColumnIndices) {
+  const auto m = CreateCompressedRowSparseMatrix();
+  const auto matcher = CompressedRowsAre(
+      std::vector{0, 2, 3}, std::vector{0, 1, 1}, std::vector{1.0, 2.0, 3.0});
+  EXPECT_THAT(*m, Not(matcher));
+  EXPECT_THAT(Explain(matcher, *m), HasSubstr("column indices"));
+}
+
+TEST(CompressedRowsAre, RejectsAdditionalRows) {
+  const auto m = CreateCompressedRowSparseMatrix();
+  EXPECT_THAT(*m,
+              Not(CompressedRowsAre(std::vector{0, 2, 3, 3},
+                                    std::vector{0, 2, 1},
+                                    std::vector{1.0, 2.0, 3.0})));
+}
+
 }  // namespace
 }  // namespace ceres::internal