Certainly! Catch2 is another popular C++ unit testing framework that is quite easy to use. Let's reframe the unit tests for the MonteCarloPiEstimator using Catch2.
Setting Up Catch2
First, download Catch2 and set it up in your environment. You can either download the single-header version from their GitHub repository or use a package manager if available.
Including Catch2 in Your Project
For simplicity, let's assume the Catch2 header file (catch.hpp) is available in your project directory.
Writing Unit Tests for MonteCarloPiEstimator
Here's how you could structure your unit tests for the MonteCarloPiEstimator class using Catch2:
MonteCarloPiEstimator.h
Ensure your class definition includes methods for accessing pi_estimates needed for testing:
#ifndef MONTECARLOPIESTIMATOR_H
#define MONTECARLOPIESTIMATOR_H
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>
class MonteCarloPiEstimator {
private:
int num_simulations;
int points_per_simulation;
std::vector<double> pi_estimates;
public:
MonteCarloPiEstimator(int simulations, int points)
: num_simulations(simulations), points_per_simulation(points) {
std::srand(static_cast<unsigned>(std::time(0))); // Seed the random number generator
}
void run_simulations() {
for (int sim = 0; sim < num_simulations; ++sim) {
int points_inside_circle = 0;
for (int i = 0; i < points_per_simulation; ++i) {
double x = (double)std::rand() / RAND_MAX;
double y = (double)std::rand() / RAND_MAX;
if (x * x + y * y <= 1.0) {
points_inside_circle++;
}
}
double pi_estimate = 4.0 * points_inside_circle / points_per_simulation;
pi_estimates.push_back(pi_estimate);
}
}
double calculate_mean() const {
double sum = 0.0;
for (double value : pi_estimates) {
sum += value;
}
return sum / pi_estimates.size();
}
double calculate_standard_deviation() const {
double mean = calculate_mean();
double sum_squared_diff = 0.0;
for (double value : pi_estimates) {
double diff = value - mean;
sum_squared_diff += diff * diff;
}
return std::sqrt(sum_squared_diff / pi_estimates.size());
}
const std::vector<double>& get_pi_estimates() const {
return pi_estimates;
}
void print_results() const {
double mean_pi = calculate_mean();
double std_dev_pi = calculate_standard_deviation();
std::cout << "Estimated Pi: " << mean_pi << std::endl;
std::cout << "Standard Deviation: " << std_dev_pi << std::endl;
}
};
#endif // MONTECARLOPIESTIMATOR_H
test_montecarlo_pi_estimator.cpp
Write your tests using Catch2:
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "MonteCarloPiEstimator.h"
TEST_CASE("MonteCarloPiEstimator runs simulations", "[MonteCarloPiEstimator]") {
MonteCarloPiEstimator estimator(100, 10000);
estimator.run_simulations();
REQUIRE(estimator.get_pi_estimates().size() == 100);
}
TEST_CASE("MonteCarloPiEstimator calculates mean correctly", "[MonteCarloPiEstimator]") {
MonteCarloPiEstimator estimator(100, 10000);
estimator.run_simulations();
double mean = estimator.calculate_mean();
REQUIRE(mean > 2.0); // Basic sanity check
REQUIRE(mean < 4.0); // Basic sanity check
REQUIRE(std::fabs(mean - 3.14) < 0.1); // Closeness to actual Pi value
}
TEST_CASE("MonteCarloPiEstimator calculates standard deviation correctly", "[MonteCarloPiEstimator]") {
MonteCarloPiEstimator estimator(100, 10000);
estimator.run_simulations();
double std_dev = estimator.calculate_standard_deviation();
REQUIRE(std_dev > 0); // Ensure standard deviation is positive
}
Explanation:
-
Including Catch2 Main Function:
#define CATCH_CONFIG_MAIN tells Catch2 to provide a main function. Only do this in one test file.
-
Test Cases:
- MonteCarloPiEstimator runs simulations: Verifies that the
run_simulations method correctly fills the pi_estimates vector.
- MonteCarloPiEstimator calculates mean correctly: Checks if the mean Pi estimate is within a reasonable range around π.
REQUIRE(mean > 2.0): A basic sanity check.
REQUIRE(mean < 4.0): A basic sanity check.
REQUIRE(std::fabs(mean - 3.14) < 0.1): Checks that the mean is close to π within an acceptable error margin.
- MonteCarloPiEstimator calculates standard deviation correctly: Ensures the standard deviation is positive.
Running the Tests
Once the tests are written, compile and run them. If you're using a build system like CMake, you can modify your CMakeLists.txt to include Catch2:
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(MonteCarloPiEstimator)
# Include directories
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
# Add source files
set(SOURCES MonteCarloPiEstimator.cpp)
# Add Catch2
include(CTest)
include(FetchContent)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v2.13.6 # Choose appropriate version
)
FetchContent_MakeAvailable(Catch2)
# Add executable for tests
add_executable(runTests test_montecarlo_pi_estimator.cpp ${SOURCES})
target_link_libraries(runTests Catch2::Catch2)
# Add test
add_test(NAME RunMonteCarloPiEstimatorTests COMMAND runTests)
Build and Run Tests
Navigate to your build directory and build the tests:
mkdir build
cd build
cmake ..
make
ctest --output-on-failure
This process will compile your tests and run them, providing output on whether they pass or fail. Catch2's descriptive error messages and simple setup make it a great choice for unit testing in C++.