Gtest和Gmock的安装使用

本文介绍了解决LNK2019错误的方法,主要是由于错误地添加了库文件导致的问题。解决方案是仅添加gtestd.lib(及gtest_maind.lib,如果不希望自行编写main函数)。并详细介绍了如何下载、编译gtest和gmock库,设置包含路径,以及如何在Visual Studio中正确链接这些库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

If you meet LNK2019 Problem

Reason: you add wrong lib.
Solution: only add gtestd.lib (and gtest_maind.lib, if don’t want to write main function by yourself).


Tutorial

In short

  1. download gtest and gmock form here.

  2. compile them into libraries and link your test with it (choose file according to your develop environment, msvc for visual studio).
    这里写图片描述
    这里写图片描述

  3. add profiles contains .h file


Detail

1. Gtest

  1. Download gtest(and gmock, if you need use its mock function).

  2. github clone project from here.
    这里写图片描述

  3. open gtest.sln.
    这里写图片描述

  4. build all under Debug( and release) mode [I don’t think we only need dug version]. Then we can get (gtestd.lib and gtest_maind.lib) for debug, (gtest.lib and gtest_maind.lib) for release.
    这里写图片描述

  5. copy four of them in a lib profile(I save it under include).
    这里写图片描述

  6. setting in your test project.

    • add lib dependencies.
      [ properties -> linker -> general ]
      这里写图片描述

    • add lib (for debug)
      Attention: only add (gtestd.lib and gtest_maind.lib), if you only want debug.(otherwise, it will has LNK2038 problem)
      这里写图片描述

    • add additional include directories
      – [ properties -> c/c++ -> additional include directories ]
      – Thus, we could write #include “gtest\gtest.h”.( you also need to add address to “gmock\gmock.h”, if you want use gmock).
      这里写图片描述

  7. change runtime library.
    – MTd for debug; MT for release.
    这里写图片描述

Write a test demo
#include <tchar.h>
#include <gtest/gtest.h>

int Foo(int a, int b)
{
    if (a == 0 || b == 0)
    {
        throw "don't do that";
    }
    int c = a % b;
    if (c == 0)
        return b;
    return Foo(b, c);
}

TEST(FooTest, HandleNoneZeroInput)
{
    EXPECT_EQ(2, Foo(4, 10));
    EXPECT_EQ(6, Foo(30, 18));
}

int _tmain(int argc, _TCHAR* argv[])
{
    testing::InitGoogleTest(&argc, argv);
    RUN_ALL_TESTS();
    system("pause");
    return 0;
}

2. Gmock

Install process is similar to gtest. It only can generate one version lib(gmock.lib), just add it to project.

A test demo: here
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值