EXPECT_CALL() 宏在尝试抛出自定义异常时无法编译

问题描述 投票:0回答:1

我有以下代码 test.cpp ,无法编译(使用 g++ test.cpp -lgtest -lgmock -pthread -lfmt 编译),我收到此错误:

无法将‘std::forward从‘CustomException’转换为‘fmt::v8::format_string<>’

这段代码的正确版本应该是什么:)?

#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();
}
c++ googletest googlemock fmt
1个回答
0
投票

这样的构造函数将起作用:

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

我填写它与P2216R3有关,通过参数展开收到的格式字符串不是constexpr。不幸的是我没有时间在文章中进行北斗潜水。

© www.soinside.com 2019 - 2024. All rights reserved.