这可能是一个愚蠢的错误,但我只是一个初学者。
我的问题如下:
我使用 Cmake 配置了 Google 测试。看起来如下:
cmake_minimum_required(VERSION 3.24)
project(TrimString_internship)
set(CMAKE_CXX_STANDARD 17)
add_executable(TrimString_internship src/main.cpp)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/5376968f6948923e2411081fd9372e71a59d8e77.zip
)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
add_executable(
hello_test
test/hello_test.cpp
)
target_link_libraries(
hello_test
GTest::gtest_main
)
add_executable(
string_trim_test
test/string_trim_test.cpp
)
target_link_libraries(
string_trim_test
GTest::gtest_main
)
include(GoogleTest)
gtest_discover_tests(hello_test)
gtest_discover_tests(string_trim_test)
我要测试的功能所在的程序如下所示:
#include <iostream>
#include <string>
template<typename Predicate>
std::string textTrim(std::string text, Predicate predicate) {
int left_character_index{0};
int right_character_index = text.length() - 1;
while (left_character_index <= right_character_index && predicate(text[left_character_index])) {
left_character_index++;
}
while (right_character_index >= left_character_index && predicate(text[right_character_index])) {
right_character_index--;
}
return text.substr(left_character_index, right_character_index - left_character_index + 1);
}
bool isWhitespace(char whitespace) {
return whitespace == ' ' || whitespace == '\t' || whitespace == '\n';
}
bool isDigit(char digit) {
return digit >= '0' && digit <= '9';
}
int main() {
std::string text = " Przykladowy string ";
std::string trimmed_text = textTrim(text, isWhitespace);
std::cout << trimmed_text << std::endl;
std::string text_1 = "12345Novomatic5678";
std::string trimmed_text_1 = textTrim(text_1, isDigit);
std::cout << trimmed_text_1 << std::endl;
}
测试如下:
#include <gtest/gtest.h>
#include "../src/main.cpp"
TEST(TextTrimTest, TrimWhiteSpace){
std::string test_text = " przykladowy string ";
std::string trimmed_test_text = textTrim(test_text, isWhitespace);
EXPECT_EQ(trimmed_test_text, "przykladowy string");
}
TEST(TextTrimTest, TrimDigits){
std::string test_text = "12345Novomatic5678";
std::string trimmed_test_text = textTrim(test_text, isDigit);
EXPECT_EQ(trimmed_test_text, "Novomatic");
}
运行上面的测试后,出现“test framework exit unexpectedly”的错误
网上查资料说原因可能是GoogleTest库配置不当,所以我创建了一个非常简单的测试来检查库是否正确安装:
#include <gtest/gtest.h>
TEST(HelloTest, BasicAssertions) {
EXPECT_STRNE("hello", "world");
EXPECT_EQ(7 * 6, 42);
}
上面的测试正确执行,“相当”证明我安装了这个库。
尝试运行“string_trim_test”时出错的原因可能是什么?