EXPECT_CALL() macro dont compile when trying to throw a custom exception

48 Views Asked by At

I have following code test.cpp , which fails to compile ( compile using : g++ test.cpp -lgtest -lgmock -pthread -lfmt), I am getting this error:

could not convert ‘std::forward<CustomException&> from ‘CustomException’ to ‘fmt::v8::format_string<>’

what should be correct version of this code :) ?

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <stdexcept>
#include <fmt/core.h>


using ::testing::_;
using ::testing::Throw;

class CustomException : public std::exception
    {
    public:
      template <typename... Args>
      explicit CustomException(Args&&... args)
          : _exception_string{fmt::format(std::forward<Args>(args)...) + _exception_suffix}
      {
      }

      inline const char* what() const noexcept override
      {
        return _exception_string.c_str();
      }

    private:
      std::string _exception_suffix{" Custom exception..."};
      std::string _exception_string{};
    };

class Calculator {
public:
    virtual double Divide(double a, double b) {
        if (b == 0.0) {
            throw std::invalid_argument("Division by zero");
        }
        return a / b;
    }
};

// Mock class for Calculator
class MockCalculator : public Calculator {
public:
    MOCK_METHOD(double, Divide, (double a, double b), (override));
};

TEST(CalculatorTest, DivideWithExceptions) {
    MockCalculator mockCalculator;

    EXPECT_CALL(mockCalculator, Divide(10.0, 0.0))
        .WillOnce(Throw(CustomException("Division by zero")));
    // Test division by zero
    try {
        double result = mockCalculator.Divide(10.0, 0.0);
        FAIL() << "Expected exception not thrown.";
    } catch (const std::invalid_argument& e) {
        EXPECT_STREQ(e.what(), "Division by zero");
    }
}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
1

There are 1 best solutions below

2
273K On

Such constructor will work:

  template <typename... Args>
  explicit CustomException(std::string_view fmt, Args&&... args)
      : _exception_string{fmt::format(fmt, std::forward<Args>(args)...) + _exception_suffix}
  {
  }

I fill it's related to P2216R3, the format string received through the unpacked parameters is not a constexpr. Unfortunately I don't have time for dipper diving into the article.