Search code examples
c++testinggoogletest

How to use matcher in google test (error: undeclared identifier)


I'm trying to use google test to test a C function. A simple test using ASSERT_NO_FATAL_FAILURE(); and also EXPECT_THAT();. But when I try to use matchers (like not null for example) the IDE says: Use of undeclared identifier 'NotNull'.

#include "gtest/gtest.h"

extern "C" {
    #include "first_tdd.h"
}

TEST(sum, sum_has_return)
{
    EXPECT_THAT(sum(), NotNull());
}
cmake_minimum_required(VERSION 3.19)
project(untitled C)

set(CMAKE_C_STANDARD 99)

add_executable(main.c sum.c)

# 'Google_test' is the subproject name
project(Google_tests)

# 'lib' is the folder with Google Test sources
add_subdirectory(googletest)
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR}, ${gmock_SOURCE_DIR}/include ${gmock_SOURCE_DIR})

# 'Google_Tests_run' is the target name
# 'test1.cpp tests2.cpp' are source files with tests
set(Sources
        sum.c
        )
add_executable(Google_Tests_run sum_tests.cpp sum.c)
target_link_libraries(Google_Tests_run gtest gtest_main)

Message when I try to run the test.

 error: use of undeclared identifier 'NotNull'
        EXPECT_THAT(sum(), NotNull());
                           ^
1 error generated.
make[3]: *** [CMakeFiles/Google_Tests_run.dir/sum_tests.cpp.o] Error 1
make[2]: *** [CMakeFiles/Google_Tests_run.dir/all] Error 2
make[1]: *** [CMakeFiles/Google_Tests_run.dir/rule] Error 2
make: *** [Google_Tests_run] Error 2

Folder Structure

Does any one know if I should include something else?

Thank you.


Solution

  • NotNull is declared in the namespace ::testing. Possible fixes

    TEST(sum, sum_has_return)
    {
        EXPECT_THAT(sum(), ::testing::NotNull());
    }
    

    or

    TEST(sum, sum_has_return)
    {
        using ::testing::NotNull;
        EXPECT_THAT(sum(), NotNull());
    }