googletest和googlemock使用总结

2014.02.26发布于笔记暂无评论/目录

googletest和googlemock使用总结,尚待补充。

googletest和googlemock是c++里很好用的单元测试框架。另外,若无特别说明,以下内容均基于googletest 1.7和googlemock 1.7。

googletest

简单的例子

Makefile

# Makefile for gtest examples
GOOGLE_TEST_LIB = gtest
GOOGLE_TEST_INCLUDE = /usr/local/include

G++ = g++
G++_FLAGS = -c -Wall -I $(GOOGLE_TEST_INCLUDE)
LD_FLAGS = -L /usr/local/lib -l $(GOOGLE_TEST_LIB) -l pthread

OBJECTS = main.o string-compare.o
TARGET = string-compare

all: $(TARGET)
 
$(TARGET): $(OBJECTS)
g++ -o $(TARGET) $(OBJECTS) $(LD_FLAGS)
  
%.o : %.cpp
$(G++) $(G++_FLAGS) $<
   
clean:
rm -f $(TARGET) $(OBJECTS)
.PHONY: all clean 

main.cpp

#include <gtest/gtest.h>
 
int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

string-compare.cpp

#include <gtest/gtest.h> // googletest header file
#include <string>
using std::string;
  
const char *actualValTrue = "hello gtest";
const char *actualValFalse = "hello world";
const char *expectVal = "hello gtest";
   
TEST(StrCompare, CStrEqual) {
    EXPECT_STREQ(expectVal, actualValTrue);
}
    
TEST(StrCompare, CStrNotEqual) {
    EXPECT_STREQ(expectVal, actualValFalse);
} 

注意事项

比较字符串

比较C String用ASSERT_STREQEXPECT_STREQ,比较std::string用ASSERT_EQEXPECT_EQ,见详细说明

googlemock

阅读资料

  1. googletest 1.7 documentation
  2. googlemock 1.7 documentation
#c++#google#单元测试#总结#未完成

评论