GithubHelp home page GithubHelp logo

sinojelly / mockcpp Goto Github PK

View Code? Open in Web Editor NEW
66.0 4.0 37.0 4.97 MB

Two C/C++ testing tools, mockcpp and testngpp.

License: Apache License 2.0

CMake 2.51% PowerShell 1.32% Makefile 1.03% Shell 0.85% C++ 83.47% C 9.31% Python 1.37% Batchfile 0.14%
testing-tools test-driven-development gtest-support catch2 mockito

mockcpp's Introduction

	mockcpp --- A C/C++ Mock Framework
	-------------------------------------
	https://github.com/sinojelly/mockcpp
	https://gitee.com/sinojelly/mockcpp

mockcpp is a jmock-like generic C/C++ Mock Framework, which doesn't use complex template technique which will result in very heavy compiling overhead.

C/C++ test framework

This project provided two tools for C/C++ testing.

Name Description Path
mockcpp C/C++ mock framework mockcpp
testngpp C/C++ test framework mockcpp/tests/3rdparty/testngpp

The sample project to use these tools is at :
https://gitee.com/sinojelly/testngpp-mockcpp-sample

You can use mockcpp with other C/C++ test framework, such as gtest, Catch2, CppUTest etc. The sample projects are at:
https://gitee.com/sinojelly/gtest-with-mockcpp
https://gitee.com/sinojelly/catch2-with-mockcpp

You can use mockcpp testngpp prebuilt libraries and header files, or use their source code.

If you use the prebuilt libraries, be sure they are built on the same os and compiler as the project that is being tested.

mockcpp features

OS Compiler Virtual method mock Global function mock Overloaded function mock
Linux GCC Yes Yes Yes
Win10 MinGW Yes Yes Yes
Win10 VS2019 Yes No Yes

testngpp features

OS Compiler Base function Memory leak check Run in Sandbox Parameterized test
Linux GCC Yes Yes Yes Yes
Win10 MinGW Yes No No Yes
Win10 VS2019 Yes Yes Yes Yes

Sample code

Testngpp parameterized test sample

FIXTURE(DataDrivenTest)
{
	DATA_PROVIDER( mydata, 3
		, DATA_GROUP(1, 2, 3) 
		, DATA_GROUP(77, 20, 97) 
		, DATA_GROUP(101, 503, 604));

	// @test(data="mydata")
	PTEST( (int a, int b, int c), this is a parameterized test)
	{
		ASSERT_EQ(c, add(a, b));
	}
};

Documents for user

New Build System Description(recommended for user and developers)
Mockcpp manual english
Mockcpp manual chinese
Mockcpp simple instruction (Chinese, recommended)
Testngpp simple instruction (Chinese, recommended)
Testngpp user manual (Chinese)

Documents for developer

Advanced Guide of Mockcpp
Mockcpp version history
Software Architecture (Chinese)
Mockcpp configure parameter
Mockcpp Build Guide (a bit old)
Mockcpp Install Guide (old)

Other documents for reference

Testngpp MSVC Installation (old)
Testngpp Introduction

Email to the current maintainers may be sent to [email protected], [email protected].

mockcpp's People

Contributors

code-in-cpp avatar fish2bird avatar github-my avatar googlecodeexporter avatar liwangqian avatar sinojelly avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

mockcpp's Issues

VS2010 error C4519: default template arguments are only allowed on a class template

系统:win10
IDE:VS2010
版本:master版本/2.7分支

Cmake选择VS2010后编译mockcpp通过,但是include到工程后,提示
“mockcpp/ChainingMockHelper.h(61): error C4519: default template arguments are only allowed on a class template”。
然后尝试使用mockcpp目录下的test确认下,也是cmake选择VS2010生成的工程,VS2010打开后,编译时同样报一样的错误:
“mockcpp/ChainingMockHelper.h(61): error C4519: default template arguments are only allowed on a class template”

ChainingMockHelper.h文件的61行是一个 "}"

template <typename V, typename D = std::default_delete<V>>
Constraint* eq(const V* val)
{
	return new IsEqual<std::unique_ptr<V, D> >(val);
} <-----line61

期望大佬回复

How can i mock nonvirtual member function?

i try to mock a nonvirtual member function, but it show me error like this:

unknown file: Failure
C++ exception with description "Virtual method address should be odd, please make sure the method long (Cfoobar::*)(long) is a virtual method" thrown in the test body.

i want to know below information:

  1. Is mockcpp support mock nonvirtual member function?
  2. if it's support, how can it do that?
// sample code
// mock target class---want to mock nonvirtual function: foobar_l
class Cfoobar {
public:
    Cfoobar() {}
    virtual ~Cfoobar() {}
    long foobar_l(long x) {return x;}
};
// unit test for this class
class CcallCfoobarByobj {
public:
    CcallCfoobarByobj() {}
    virtual ~CcallCfoobarByobj() {}
    Cfoobar cfoobar;
    long callfoobar_l(long x) {return cfoobar.foobar_l(x);}
};
// unit test case
TEST(verifyMockcpp, memberFunctionByObj_Mock) {
    MockObject<Cfoobar> mocker;
    MOCK_METHOD(mocker, foobar_l).stubs().will(returnValue(36));

    CcallCfoobarByobj obj;
    EXPECT_EQ(obj.callfoobar_l(2), 36);
    mocker.verify();
    EXPECT_EQ(obj.callfoobar_l(2), 2);
}

Can't work right under cygwin

What steps will reproduce the problem?
A simple one file teset:

#include <gtest/gtest.h>
#include <mockcpp/mockcpp.hpp>

void func()
{
    std::cout<<"In real func\n";
}

TEST(Test, should_call_func_once)
{
    MOCKER(func)
            .expects(once());
    func();
    GlobalMockObject::verify();
}

int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

What is the expected output? What do you see instead?
I expect TEST pass, but I got:
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from Test
[ RUN      ] Test.should_call_func_once
In real func
/cygdrive/d/mockcpp/mockcpp/src/ChainableMockObjectBase.cpp:85: Failure
Invocation is expected only once(), but it's been invoked 0 times
method(func)
     .expects(once())
     .invoked(0);
unknown file: Failure
C++ exception with description "failed due to mockcpp exception" thrown in the 
test body.
[  FAILED  ] Test.should_call_func_once (0 ms)
[----------] 1 test from Test (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] Test.should_call_func_once

 1 FAILED TEST

What version of the product are you using? On what operating system?
Windows XP, cygwin(gcc/g++ 4.5.3), gtest 1.6.0, mockcpp 2.6

Please provide any additional information below.

Original issue reported on code.google.com by [email protected] on 27 Jul 2012 at 2:23

ProcStub may cause coredump when invoke a function be mocked concurrently

I found this problem in my job, to reproduce that problem, the simplified model is as follows:

int echo()
{
    return 0;
}

TEST(ProcStubTest, test1)
{
    MOCKER(echo)
        .stubs()
        .will(invoke(+[]{
            return 1;
        }));
    std::vector<std::thread> thds;
    for ( int i = 0; i < 4; i++ )
    {
        thds.emplace_back([]{
            for ( int i = 0; i < 100; i++ )
            {
                EXPECT_EQ(1, echo());
            }
        });
    }
    for ( auto&& t : thds )
    {
        t.join();
    }
    GlobalMockObject::verify();
}

problem:
when invoke the function be mocked concurrently,the operator= of result (member of ProcStub object) will be invoked concurrently, however, it's not thread safe, may cause double free/accessing freed memory etc..
image
image
image

In order to test my conclusion, I add a mutex for ProcStub as follows:

MOCKCPP_NS_START
template <typename F>
struct ThreadSafeProcStub;
#define THREAD_SAFE_PROC_STUB(n)                                                              \
template <typename R DECL_TEMPLATE_ARGS(n)>                                                   \
struct ThreadSafeProcStub<R(DECL_ARGS(n))> : public ProcStubBase                              \
{                                                                                             \
    public:                                                                                   \
        typedef R (*Func)(DECL_ARGS(n));                                                      \
        ThreadSafeProcStub(Func f, std::string name) : ProcStubBase(name, (void*)f), func(f){}\
        Any& invoke(const Invocation& inv)                                                    \
        {                                                                                     \
            SIMPLE_REPEAT(n, MOCKCPP_CHECK_AND_ASSIGN_PARAMETER);                             \
            Any tmp = func(DECL_PARAMS(n));                                                   \
            std::lock_guard<std::mutex> lck{mtx};                                             \
            results.emplace_back(tmp);                                                        \
            return results.back();                                                            \
        }                                                                                     \
    private:                                                                                  \
        Func            func;                                                                 \
        std::mutex      mtx;                                                                  \
        std::list<Any>  results;                                                              \
};                                                                                            \
template <typename R DECL_TEMPLATE_ARGS(n)>                                                   \
Stub* invoke_thread_safe(R(*f)(DECL_ARGS(n)), const char* name = 0)                           \
{                                                                                             \
    return new ThreadSafeProcStub<R(DECL_ARGS(n))>(f, name ? name : "");                      \
}
THREAD_SAFE_PROC_STUB(0);
THREAD_SAFE_PROC_STUB(1);
THREAD_SAFE_PROC_STUB(2);
THREAD_SAFE_PROC_STUB(3);
THREAD_SAFE_PROC_STUB(4);
THREAD_SAFE_PROC_STUB(5);
THREAD_SAFE_PROC_STUB(6);
THREAD_SAFE_PROC_STUB(7);
THREAD_SAFE_PROC_STUB(8);
THREAD_SAFE_PROC_STUB(9);
THREAD_SAFE_PROC_STUB(10);
THREAD_SAFE_PROC_STUB(11);
THREAD_SAFE_PROC_STUB(12);
MOCKCPP_NS_END

int echo()
{
    return 0;
}

TEST(ProcStubTest, test1)
{
    MOCKER(echo)
        .stubs()
        .will(invoke_thread_safe(+[]{
            return 1;
        }));
    std::vector<std::thread> thds;
    for ( int i = 0; i < 4; i++ )
    {
        thds.emplace_back([]{
            for ( int i = 0; i < 100; i++ )
            {
                EXPECT_EQ(1, echo());
            }
        });
    }
    for ( auto&& t : thds )
    {
        t.join();
    }
    GlobalMockObject::verify();
}

It seems works and no longer cause coredump(although the implementation may not be so graceful).

Compile error

What steps will reproduce the problem?
1. cmake
2. make fails, never got to "make install"

[ 98%] Building CXX object 
src/CMakeFiles/mockcpp.dir/ports/failure/cppunit_report_failure.cpp.o
/home/dmccracken/mockcpp-2.5-20110326/src/ports/failure/cppunit_report_failure.c
pp:23: error: expected constructor, destructor, or type conversion before "void"
/home/dmccracken/mockcpp-2.5-20110326/src/ports/failure/cppunit_report_failure.c
pp:31: error: expected constructor, destructor, or type conversion at end of 
input
*** Error code 1
clearmake: Error: Build script failed for 
"src/CMakeFiles/mockcpp.dir/ports/failure/cppunit_report_failure.cpp.o"
clearmake[2]: Leaving directory `/home/dmccracken/mockcpp-2.5-20110326'
*** Error code 1
clearmake: Error: Build script failed for "src/CMakeFiles/mockcpp.dir/all"
clearmake[1]: Leaving directory `/home/dmccracken/mockcpp-2.5-20110326'
*** Error code 1
clearmake: Error: Build script failed for "all"



mockcpp version 2.5

OS Version: Linux hornetdev8.eng.sonusnet.com 2.6.9-55.ELsmp #1 SMP Fri Apr 20 
16:36:54 EDT 2007 x86_64 x86_64 x86_64 GNU/Linux



Original issue reported on code.google.com by [email protected] on 28 Sep 2011 at 5:33

how can i mock overloaded template functions

i try to mock overloaded template functions:

template <typename M>
  void publish(const boost::shared_ptr<M>& message) const
{
  //do
}

template <typename M>
  void publish(const M& message) const
{
  //do
}

my code is :

MOCKER((void(ros::Publisher::*)(const map_service::MapChanged &))&ros::Publisher::publish<const map_service::MapChanged &>)
.stubs();

i want to mock the second template function, but it doesn't work.
Thanks for your help!

mockcpp在c++20 无法生效

工程是gtest+mockcpp
** linux版本:** ubuntu 22.04
Linux openbmc 6.5.0-35-generic #35~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Tue May 7 09:00:52 UTC 2 x86_64 x86_64 x86_64 GNU/Linux

** gcc版本:** gcc (Ubuntu 12.3.0-1ubuntu1~22.04) 12.3.0
** c++标准:** c++20

** 代码:**

#include "gtest/gtest.h"
#include "mockcpp/mockcpp.hpp"

int add(int value1, int value2) {
        return value1 + value2;
}


TEST(MOCK, mock_function_test)
{
    MOCKER(add)
        .stubs()
        .will(returnValue(100));
    int value = add(1, 2);

    ASSERT_EQ(100, value);
}

** 执行结果:**
[----------] 1 test from MOCK
[ RUN ] MOCK.mock_function_test
../test/src/mock/MockTest.cpp:16: Failure
Expected equality of these values:
100
value
Which is: 3
[ FAILED ] MOCK.mock_function_test (0 ms)
[----------] 1 test from MOCK (0 ms total)

Two TestFormatter tests failed on Visual Studio 2019

The failed tests are:

--------------------SUITE: TestFormatter--------------------

(TestFormatter)
.................
[  FAILED  ] testShouldBeAbleToStringnizeVerySmallDouble - TestFormatter.h:234: expected (expected == toTypeAndValueString(d)), found ((std::string)"(double)1e-022" != (std::string)"(double)1e-22")
.....
[  FAILED  ] testShouldBeAbleToStringnizeVerySmallFloat - TestFormatter.h:280: expected (expected == toTypeAndValueString(f)), found ((std::string)"(float)1e-022" != (std::string)"(float)1e-22")

怎么取消指定MOCKER

GlobalMockObject::verify(); 或者GlobalMockObject::reset();可以取消所有的MOCKER,但是,如果我想保留一部分MOCKER,只取消另一部分MOCKER,需要怎么做?

while running in linux multi-thread, maybe have coredump

sample test code:
`#include <stdio.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <unistd.h>
#include "gtest/gtest.h"
#include "mockcpp/mokc.h"

int int_ret_func(int a, int b)
{
printf("call orginal function %s\n", FUNCTION);
return a + b;
}

int stub_int_ret_func(int a, int b)
{
int tid = (int)syscall(__NR_gettid);
printf("call stub function %s, tid: %d\n", FUNCTION, tid);
return a * b;
}

void void_ret_func(int a, int b, int c)
{
printf("call orginal function %s\n", FUNCTION);
}

void stub_void_ret_func(int a, int b, int c)
{
int tid = (int)syscall(__NR_gettid);
printf("call stub function %s, tid: %d\n", FUNCTION, tid);
}

void *threadFunc(void *arg)
{
while (1) {
int ret = int_ret_func(2, 3);
EXPECT_EQ(ret, 6);
void_ret_func(2, 3, 4);
usleep(1000);
}

return NULL;

}

TEST(TestSuite, Factorial_Stub)
{
MOCKER(int_ret_func).stubs().will(invoke(stub_int_ret_func));
MOCKER(void_ret_func).stubs().will(invoke(stub_void_ret_func));

#define TID_CNT 8
pthread_t tid[TID_CNT];
for (int loop = 0; loop < TID_CNT; loop++) {
    pthread_create(&tid[loop], NULL, &threadFunc, NULL);
}

for (int loop = 0; loop < TID_CNT; loop++) {
    pthread_join(tid[loop], NULL);
}

}`
running result:
image

because of data using after free, need to fix

EnglishManual mistake

The EnglishManual had a mistake:

    Output through pointer: outBound(point, constraint) 
should be
    Output through pointer: outBoundP(point, size, constraint) 

And it's better to add examples for outBound/outBoundP into EnglishManual.
I have many foreign follows using testngpp/mockcpp.

Thanks.

Original issue reported on code.google.com by [email protected] on 18 Jan 2013 at 4:08

MOCKER(write) 报 Segmentation fault (core dumped) 错误

操作系统:Ubuntu 22.10
Linux ubuntu22-xxx 5.19.0-35-generic #36-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb 3 18:36:56 UTC 2023 x86_64 x86_64 x86_64
GNU/Linux

[root@xxx ~]# cat /etc/os-release
PRETTY_NAME="Ubuntu 22.10"
NAME="Ubuntu"
VERSION_ID="22.10"
VERSION="22.10 (Kinetic Kudu)"
VERSION_CODENAME=kinetic
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=kinetic
LOGO=ubuntu-logo

编译器:gcc 12.2
[root@xxx ~]# gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/12/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 12.2.0-3ubuntu1' --with-bugurl=file:///usr/share/doc/gcc-12/README.Bugs --enable-languages=c,ada,c++,go,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-12 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-12-U8K4Qv/gcc-12-12.2.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-12-U8K4Qv/gcc-12-12.2.0/debian/tmp-gcn/usr --enable-offload-defaulted --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 12.2.0 (Ubuntu 12.2.0-3ubuntu1)

mockcpp 版本:2.7
gtest 版本:1.13.0
下载地址:
https://github.com/sinojelly/mockcpp/archive/refs/tags/v2.7.zip
https://github.com/google/googletest/archive/refs/tags/v1.13.0.zip
编译运行步骤:

  1. 在 /tmp 目录下创建文件夹
    cd /tmp
    mkdir gtest_mockcpp
    cd gtest_mockcpp
    mkdir 3rd
    mkdir 3rd/gtest
    mkdir 3rd/mockcpp
  2. 下载 mockcpp-2.7.zip、googletest-1.13.0.zip并解压
    unzip mockcpp-2.7.zip
    unzip googletest-1.13.0.zip
  3. 编译、安装 gtest
    cd /tmp/gtest_mockcpp/googletest-1.13.0
    修改 CMakeLists.txt文件添加 :
    set(CMAKE_INSTALL_PREFIX ${CMAKE_CURRENT_SOURCE_DIR}/../3rd/gtest)
    set(CMAKE_CXX_FLAGS "-std=c++14 -g -Wall -fPIE -pie -O0")
    编译安装
    mkdir cmake && cd cmake
    cmake ..
    make
    make install
  4. 编译、安装 mockcpp
    cd /tmp/gtest_mockcpp/mockcpp-2.7
    修改 build_install.sh:
    set -e 改为
    set -e
    CURRENT_DIR=$(cd `dirname $0`; pwd)
    INSTALL_PATH=~/test_tools/mockcpp_install 改为 INSTALL_PATH=${CURRENT_DIR}/../3rd/mockcpp
    XUNIT_NAME=testngpp 改为 #XUNIT_NAME=testngpp
    #XUNIT_NAME=gtest 改为 XUNIT_NAME=gtest
    #XUNIT_HOME=/usr/local 改为 XUNIT_HOME=${CURRENT_DIR}/../3rd/gtest
    修改 CMakeLists.txt 加上 set(CMAKE_CXX_STANDARD 14) 编译选项
    执行sh build_install.sh
  5. 准备测试用例
    cd /tmp/gtest_mockcpp
    mkdir code && cd code
    vim CMakeLists.txt
    vim test_main.cpp

测试用例:
CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
PROJECT(mockcpp_demo)
set(targetname mockcpp_demo)


set(CMAKE_CXX_FLAGS "-std=c++14 -g -Wall -fPIE -pie  -O0")
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)


set(CURRENT_DIR ${CMAKE_CURRENT_SOURCE_DIR})
#******************************** DTFramework_C 配置 ************************
# 指定对应的头文件目录、静态库目录
if (NOT DEFINED DT_C_DIR)
    set(DT_C_DIR "${CURRENT_DIR}/../3rd")
endif ()

LINK_DIRECTORIES(${DT_C_DIR}/mockcpp/lib)
INCLUDE_DIRECTORIES(${DT_C_DIR}/mockcpp/include)

LINK_DIRECTORIES(${DT_C_DIR}/gtest/lib64)
INCLUDE_DIRECTORIES(${DT_C_DIR}/gtest/include)


add_executable(${targetname} test_main.cpp)
target_link_libraries(${targetname}  -pie -Wl,--start-group   pthread dl gtest gtest_main mockcpp -Wl,--end-group )

install(TARGETS ${targetname}
        RUNTIME  DESTINATION ${CMAKE_SOURCE_DIR}/output)

test_main.cpp

#include "gtest/gtest.h"
#include "mockcpp/mockcpp.hpp"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <cstdio>
#include <unistd.h>
#include <stdlib.h>

using namespace std;

ssize_t writeTest(int fd, const void *buf, size_t count) {
    cout << "line "<<__LINE__ << endl;
    cout << "3======" << endl;
    string absFileName = "./file.txt";
    fd = open(absFileName.c_str(), O_CREAT | O_RDWR | O_TRUNC, S_IREAD | S_IWRITE);
    string cipherKey = "asdfghjkl";
    int ret = write(fd, cipherKey.c_str(), cipherKey.length());
    close(fd);
    cout << "4======" << endl;
    cout << "line " <<__LINE__<< endl;
    return 3;
}


class Test_Demo_Suit : public testing::Test {
public:
    static void SetUpTestCase()
    {
        /*SetUpTestCase该函数在每个用例套执行前会执行*/
    }

    static void TearDownTestCase()
    {
        /* 该函数在每个用例套执行后会执行 */
    }

    virtual void SetUp()
    {
    }

    virtual void TearDown()
    {
        /* 该函数在每个测试用例执行完成后会执行 */
        GlobalMockObject::verify();
    }
};


TEST(UnitTest, writeToOpen) {
    cout << "line "<<__LINE__ << endl;
    MOCKER(write).defaults().will(invoke(writeTest));
    cout << "line "<<__LINE__ << endl;
}



int main(int argc, char* argv[]) {
    printf("\n hello,world");
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

报错信息:
[root@xxx cmake]# mockcpp_demo

hello,world[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from UnitTest
[ RUN ] UnitTest.writeToOpen
line 56
Segmentation fault

Can not use MOCKER(malloc) to mock malloc

If you use MOCKER(malloc) to mock malloc function, it crash.

because mockcpp need malloc.

I think, maybe we can use MOCKABLE(malloc) to mock malloc.

But, we can't use MOCKER and MOCKABLE at the same time now.


Original issue reported on code.google.com by [email protected] on 21 Mar 2011 at 3:50

2.7版本删除了以前版本提供的MOCKER_CPP宏?

int32_t func1Stub(Class1*o, int32_t in, int32_t &out)
{
    if (in >=1) {
        out = 1;
    } else {
        out = 0;
    }
    return 0;
}

MOCKER_CPP(&Class1::func1, int32_t (Class1::*)(int32_t, int32_t&)).defaults().will(invoke(func1Stub));

早期版本可以对类的普通函数这么打桩。在2.7版本中有什么替换方案?

mockcpp does not build against latest googletest 1.13

The main branch of mockcpp does not build against the latest version of googletest (v1.13 onwards) when specifying gtest as the unit test framework. The build fails when building ports/failure/gtest_report_failure.cpp.o because the included gtest.h forces an error with a message about the compiler being required to support C++14.

This was seen on Windows, using both cygwin and WSL Ubuntu.

This error occurs because the mockcpp build enforces c++11 compilation. The relevant code is in src/CMakeLists.txt::83:

IF(MSVC)
    ADD_DEFINITIONS(-DMSVC_VMG_ENABLED) #  /Z7)
    SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /vmg")
	INCLUDE_DIRECTORIES(BEFORE ${MOCKCPP_SRC_ROOT}/3rdparty/msinttypes)
ELSE(MSVC)
    ADD_DEFINITIONS(-std=c++11)
ENDIF(MSVC)

When the -std flag is removed, the latest version of googletest builds without problem.
Presumably the enforcing -std flag is there for a reason, but can it be either removed completely, or removed for gtest dependency?

compile error

class mock_appframe : public mockcpp::ChainableMockObject

mock_appframe* mock_appframe::Alloc(int iDataSize)
{
    return invoke<mock_appframe*>("Alloc")(iDataSize);
}

error: cannot call member function `mockcpp::ChainableMockMethod<RT> 
mockcpp::ChainableMockObject::invoke(const std::string&) const [with RT = 
mock_appframe*]' without object

Original issue reported on code.google.com by [email protected] on 23 May 2009 at 2:38

Android Termux + Clang环境下mockcpp存在的问题

这个运行环境是比较少见的,mockcpp起初也没考虑这样的运行环境,它的很多特性跟编译器关系很大,所以会存在较多问题。
1、虚接口mock报错。mockcpp认为它可能不是虚接口。
2、ApiHook报错,Illegal Instruction.
3、InterfaceInfo测试不过,未抛出预期的异常。
4、格式相关测试有不通过的。
参见下图
Screenshot_20210407_203712_vn vhn vsc

Screenshot_20210407_203851_vn vhn vsc

Screenshot_20210407_203753_vn vhn vsc

Screenshot_20210407_203816_vn vhn vsc

in Googletest, mockcpp throw C++ exception lead to subsequent testcase timeout

OS: Ubuntu 18.04
Compiler: Clang15.0.6
Googletest: Googletest 1.13.0
mockcpp: 2.7

func.c
int add(int a, int b){
return a+b;
}

func.h
int add(int a, int b);

mockcpp.cpp
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "mockcpp/mockcpp.hpp"
extern "C" {
#include "func.h"
}

TEST(mockcpp, test_basic_add){
//This is a simple case to get mockcpp exception
MOCKER(add).expects(once()).with(eq(2),eq(2)).will(returnValue(4));
int ret;
ret = add(1,2);
EXPECT_EQ(ret, 3);
GlobalMockObject::verify();
}

TEST(mockcpp, test_basic_add_timeout){
int ret;
//time out when call mock object
ret = add(2,3);
EXPECT_EQ(ret, 5);
}

int main(int argc, char *argv[]) {
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}

As the title says, mockcpp will throw an exception at the end of the test_basic_add case.
in this case, because there is no execution that matched argument function.
But in the next testcase, it will timeout when calling add, although we have called the verify() function

Observed from the debugger tool, it is stuck on mockcpp::ApiHookFunctor() ApiHookFunctor.h:168:1
-> std::mutex::lock

So I would like to ask if it is possible to provide a more comprehensive function than verify to clear all settings (including unlock mutex)
We can put it in the SetUp, so that each testcase has a clean environment
Or, is there any suitable solution to avoid this problem?

thanks
-Sam

outBoundP 该怎么使用呢?大神们帮忙看看吧~!

最近项目中用到mockcpp当需要调用带有输出指针参数的函数时遇到问题,代码如下 ;

void function(int32_t *val)
{
}
int32_t expect = 10;
int32_t* bb = (int32_t*)malloc(sizeof(int32_t));
MOCKER(function).stubs().with(outBoundP(&expect, sizeof(expect)));
function(bb);
EXPECT_EQ(*bb, 10);
这里会在调用function时报错误 0xC0000005: 读取位置 0x0000000000007FF7 时发生访问冲突。
不知道这里到底怎么使用? 环境windos10 +visual studio 2017 +mockcpp 2.6

Compile error when using API Hook on Visual Studio 2019

The error information is:

mockcpp/ApiHookGenerator.h(52,34): error C2039:  'freeApiHook': is not a member of 'mockcpp::ApiHookFunctor<F,10>'

I think this issue may be related to the code below in https://github.com/sinojelly/mockcpp/blob/master/include/mockcpp/ApiHookFunctor.h

#if _MSC_VER >= 1920    // VS 2019 
#define MOCKCPP_API_HOOK_FUNCTOR_DEF(n) \
__MOCKCPP_API_HOOK_FUNCTOR_DEF(n, __stdcall)
#else
#define MOCKCPP_API_HOOK_FUNCTOR_DEF(n) \
__MOCKCPP_API_HOOK_FUNCTOR_DEF(n, ); \
__MOCKCPP_API_HOOK_FUNCTOR_DEF(n, __stdcall) 
#endif

Maybe some template features changed in Visual Studio 2019, so the code above must be modified to compile pass.
I just have modified it to pass the compilation, but not test using API hook tests (they crashed now, see #18 ).

Whether CMAKE_SOURCE_DIR can be changed to PROJECT_SOURCE_DIR?

SET(MOCKCPP_SRC_ROOT ${CMAKE_SOURCE_DIR})

When I compiled mockcpp in my test code directory, CMAKE_SOURCE_DIR points to my root directory, which leads to the wrong path at compile time.I suggest changing it to PROJECT_SOURCE_DIR.
My directory structure is as follows:

linux-jbfy:~/demo # tree
.
├── CMakeLists.txt          # CMAKE_SOURCE_DIR is "~/demo"
├── testcase                # my testcase folder
├── mockcpp
│   ├── CMakeLists.txt      # PROJECT_SOURCE_DIR is "~/demo/mockcpp"
│   ├── src
│   │   ├── CMakeLists.txt  # use CMAKE_SOURCE_DIR, and get wrong path"~/demo", should be "~/demo/mockcpp"
...

stubs() does not take effect

1、code
static int add(int left, int right)
{
return left + right;
}

TEST(ft_test, demo)
{
GlobalMockObject::reset();
MOCKER(add).stubs().with(any()).will(returnValue(300));
EXPECT_EQ(300, add(1, 4));
}

2、test result
[ RUN ] ft_test.demo
/home/tangshp/Code_ws/googleTest_mockcpp/test/ft_test.cpp:13: Failure
Expected equality of these values:
300
add(1, 4)
Which is: 5
[ FAILED ] ft_test.demo (0 ms)
[----------] 1 test from ft_test (0 ms total)

3、googletest+mockcpp
mockcpp-build-step:
➜ build xunit_home=/usr/local
➜ build cmake -DMOCKCPP_XUNIT=gtest -DMOCKCPP_XUNIT_HOME=$xunit_home -DCMAKE_INSTALL_PREFIX=/usr/local ..
➜ build sudo make && make install

MinGW delete mock对象会异常退出

`
void testShouldSupportDeleteAMockObjectWhoMocksASimpleInterface()
{
MockObject mock;

  Base1* p = mock;

  delete p;

}
`

[ RUN ] TestMockObject2::TestMockObject2::testShouldSupportDeleteAMockObjectWhoMocksASimpleInterface

MinGW 的 new/delete 行为,与其它有差异。
已经在 mem_checker/debug_new.cpp 中定义 NOT_USE_MEM_CHECKER 宏,避免 new/delete 重载导致问题。
还是遇到 delete mock对象出错。说明编译器确实在 delete 行为方面有差异。

MinGW GCC 8 compile error.

Maybe because the pointer is 8 bytes, not 4 bytes.

[ 95%] Building CXX object src/CMakeFiles/mockcpp.dir/JmpCode.cpp.obj
In file included from D:\Develop\work\mockcpp\src\JmpCodeArch.h:25,
                 from D:\Develop\work\mockcpp\src\JmpCode.cpp:22:
D:\Develop\work\mockcpp\src\JmpCode.cpp: In constructor 'mockcpp::JmpCodeImpl::JmpCodeImpl(const void*, const void*)':
D:\Develop\work\mockcpp\src\JmpCode.cpp:34:34: error: cast from 'const void*' to 'long unsigned int' loses precision [-fpermissive]
       SET_JMP_CODE(m_code, from, to);
                                  ^~
D:\Develop\work\mockcpp\src\JmpCodeX86.h:23:28: note: in definition of macro 'SET_JMP_CODE'
             (unsigned long)to - (unsigned long)from - sizeof(jmpCodeTemplate); \
                            ^~
D:\Develop\work\mockcpp\src\JmpCode.cpp:34:28: error: cast from 'const void*' to 'long unsigned int' loses precision [-fpermissive]
       SET_JMP_CODE(m_code, from, to);
                            ^~~~
D:\Develop\work\mockcpp\src\JmpCodeX86.h:23:48: note: in definition of macro 'SET_JMP_CODE'
             (unsigned long)to - (unsigned long)from - sizeof(jmpCodeTemplate); \
                                                ^~~~
make[2]: *** [src\CMakeFiles\mockcpp.dir\build.make:1160: src/CMakeFiles/mockcpp.dir/JmpCode.cpp.obj] Error 1
make[1]: *** [CMakeFiles\Makefile2:115: src/CMakeFiles/mockcpp.dir/all] Error 2

GCC compile warning: \mockcpp\include/mockcpp/mockcpp.h:59:1: Warning:identifier ‘static_assert’ is a keyword in C++11

====What steps will reproduce the problem?
Any test project including mockcpp under following enviorment will produce this 
problem.

=====What is the expected output? What do you see instead?
I don't want to have this warning. It make Eclipse/CDT think something wrong 
with test project, and I have to force Eclipse/CDT run executable everytime.

====What version of the product are you using? On what operating system?
version 2.6, Windows XP, MinGW, gcc 4.7.2. Eclipse/CDT

=====Please provide any additional information below.
This cause mockcpp.h define a struct called static_assert which confict with 
keyword of C++11.

Original issue reported on code.google.com by [email protected] on 8 Jan 2013 at 12:56

outbound does not work when mock a member fucntion of a class with a output parameter

I want to use mockcpp to mock a member function of a class. The member function 
has a output parameter. I want to assign the value of the output parameter. but 
it doesnot work. Compilation can complete successfullly. But the output 
parameter is not assigned the mocked value. My code is below:

class Parameter
{
public:
int a;
Parameter() {a=0;}
}

class MyClass
{
public:
virtual void func(Parameter &b) { b.a = 1;}
}

Parameter p;
p.a = 2;
MockObject<MyClass> mocker;
MOCK_METHOD(mocker,  func ).stubs().with(outBound(p));

When MyClass::func is invoked, the output parameter p.a is not 2, but 1.


Original issue reported on code.google.com by [email protected] on 14 Aug 2014 at 2:52

Visual Studio 2019 API Hook doesn't work

The crashed tests are:

---------------------SUITE: TestApiHook---------------------

(ApiHook)
[  ERROR   ] can mock C function - TestApiHook.h:66: hardware exception STATUS_ACCESS_VIOLATION raised in setup or running test
[  ERROR   ] can mock C function - TestApiHook.h:66: hardware exception STATUS_ACCESS_VIOLATION raised in teardown
-------------------SUITE: TestApiHookBase-------------------

(ApiHookBase)
[  ERROR   ] can mock C function with no return and no parameter - TestApiHookBase.h:148: hardware exception STATUS_PRIVILEGED_INSTRUCTION raised in setup or running test
[  ERROR   ] can mock C function with no return and no parameter - TestApiHookBase.h:148: hardware exception STATUS_PRIVILEGED_INSTRUCTION raised in teardown
-----------------SUITE: TestApiHookStdcall------------------

(ApiHookStdcall)
[  ERROR   ] can mock stdcall C function - TestApiHookStdcall.h:60: hardware exception STATUS_ACCESS_VIOLATION raised in setup or running test
[  ERROR   ] can mock stdcall C function - TestApiHookStdcall.h:60: hardware exception STATUS_ACCESS_VIOLATION raised in teardown

The API Hook actually modifies a few bytes at the entry of the function to a jmp instruction that jumps to another stub function. VS 2019 does not work in this way, probably because of adding a new protection to the code segment. If you have any information, you are welcome to provide clues or submit a PR.

API Hook 实际上是修改了代码段函数入口处的几个字节,把它改成了跳转到另外一个stub函数的jmp指令。VS 2019这种方式不可工作,可能是对代码段的修改增加了新的保护措施。如果有人了解相关信息,欢迎提供线索或者提交PR。

utf-8编码的测试用例在WinXP 32 +VC2005平台不能正确处理

TestMockObject.cpp
..\..\mockcpp\mockcpp\tests\ut\TestMockObject.cpp : warning C4819: 
该文件包含不能在当前代码页(936)中表示的字符
。请将该文件保存为 Unicode 格式以防止数据丢失
F:/tools_release/mockcpp_exported_1201/mockcpp/mockcpp/tests/ut/TestMockObject.h
 : warning C4819: 该文件包含不
能在当前代码页(936)中表示的字符。请将该文件保存为 Unicode 
格式以防止数据丢失
using native typeof
F:/tools_release/mockcpp_exported_1201/mockcpp/mockcpp/tests/ut/TestMockObject.h
(123) : fatal error C1057: 宏
展开中遇到意外的文件结束

Original issue reported on code.google.com by [email protected] on 1 Dec 2010 at 3:12

There is a link error if I use MOCKCPP_USE_MOCKABLE in my test project.

What steps will reproduce the problem?
1. Compile and install mockcpp in default configuration. 
2. Compile my test project, with /DMOCKCPP_USE_MOCKABLE.
3. (VS2005) Generation the following link error:
ut.obj : error LNK2001: "public: static class mockcpp::ChainableMockObject 
mockcpp::GlobalMockObject:
:instance" (?instance@GlobalMockObject@mockcpp@@2VChainableMockObject@2@A)

What version of the product are you using? On what operating system?
mockcpp 2.4, Windows XP and Visual Studio 2005.

Please provide any additional information below.
I think it may be better to provider a new cmake entry for 
MOCKCPP_USE_MOCKABLE. 

Original issue reported on code.google.com by [email protected] on 19 Apr 2010 at 5:50

When testing C code, the checker throws an exception. The actual parameter of the C code cannot be unique_ptr, which is the syntax of C++11.

return new IsEqual<std::unique_ptr<V, D> >(val);

sample code:

#include "sample3.h"

static unsigned char g_data = 0;

void save_data(const Sample3 *s)
{
    g_data = s->a + s->b;
}

int test(const Sample3 *s)
{
    if ((s->a >= 0x80) && (s->b >= 0x80)) {
        return -1;
    } else {
        save_data(s);
        return 0;
    }
}

testcase:

TEST_F(TestSuite3, T2)
{
    Sample3 t = {1, 2};
    MOCKER(save_data).stubs().with(eq((const Sample3*)&t));

    auto ret = test(&t);

    EXPECT_EQ(ret, 0);
}

test result:

[ RUN      ] TestSuite3.T2
unknown file: Failure
C++ exception with description "
=====================================
Unexpected invocation: the invocation cannot be found in allowed invoking list.
Invoked: save_data((Sample3 const*)0x7fff442b0630)
Allowed: 
method(save_data)
     .stubs()
     .invoked(0)
     .with(eq(unique_ptr (Sample3 const*)0x7fff442b0630));

=====================================
" thrown in the test body.

Does the ARM-Linux platform support it?

I cross-compiled the arm version library with the latest code, and the cross-compiler is gnu-6.5.0.
During the test, it is found that when the arm platform is running, coredump will be called by the function of mock.
The read function is the function of mockcpp piling.
image

Thank you for the answer!

why Mock does not work?

after i mock a c++ class function, my program still go into the function i mocked.
but, in the same folder, same CMakeLists.txt, another test_cpp file could mock successful.
my project folder like this:
a.cpp
{
b.func();
}
b.cpp
main.cpp
CMakeLists.txt
my test folder :
test_a.cpp
test_b.cpp
test_main.cpp
i want to use b.cpp's function in a.cpp, and i mock b.func in a.cpp for test a.func.

TestXXX.so.so not found issue

If use TestXXX.so in the command line, should remove .so in the name, ref to:sinojelly/test-ng-pp@c443925

仅参考上面一句话可能无法解决。此问题背景:
Linux上(A)已经编译了testngpp的二进制文件,直接放到另外一个Linux电脑(B)运行。
发现 TestXXX.so.so找不到。这可能有两个原因:
1、不支持 TestXXX.so 直接使用到命令行中,testngpp runner加载so的时候,再次追加一个 .so。(这种可能性小,因为B上直接源码编译testngpp,是可以运行的)
2、TestXXX.so 依赖于别的库,导致它加载失败,从而 testngpp runner 追加.so,再次尝试加载,还是失败。(这种情况就需要定位 TestXXX.so 为何加载失败,看起来它依赖于 libtestngpp.so 库,用的是本地路径,应该也是可以加载成功的)

如果命令行直接改成 TestXXX 名字,则看起来 so 加载成功了,但是 在 so 中找符号会失败:
test suite "libadder-ut-TestAdder" can't be loaded : libadder-ut-TestAdder.so: undefined symbol: _ZNK7mockcpp23ChainableMockObjectBase7getNameEv

bug: linux use large page memory, function stubs failed

mprotect for change function head instructions in memory.
current code use 4K size page, in normal machine should be OK;
but in large page (such as 2M size) mechine, mprotect system call return failed, because memory size not in bound.
so here gives a fix, read page size from kernel config, then set mprotect the right size.
image

单独取消mock的疑问

在mock过程中增加了许多接口的mock,但是无法单独取消某个接口mock,
使用verify()后会全部取消。
请问有没有办法在verify后,保留之前的mock内容?

how to use checkWith?

the source code is:
bool checkGlobalEnable(void* vpIn)
{
    mux_switch_conf_t* pMux = (mux_switch_conf_t*)vpIn;
    return (MUX_ENABLE == pMux->arg) ? true : false;
}

MOCKER(msMux_IoCtrl)
        .expects(once())
            .with(eq(IOCTRL_CLASS_MSAN_SWITCH_INTF), eq(DRV_SET_DHCP_EN), checkWith(checkGlobalEnable), any(), any())
            .will(returnValue(0));

then compiled in vs2005 failed:
using native typeof
1>c:\syy\mockcpp\include\mockcpp\chainingmockhelper.h(103) : error C2825: 
'Predict': must be a class or namespace when followed by '::'
1>        
e:\testngpp\myprj\nppkt\nppkt\unittest\testcase\test_nppkt_pktctrl.h(53) : see 
reference to function template instantiation 'mockcpp::Constraint 
*mockcpp::checkWith<int(__cdecl *)(void *)>(Predict)' being compiled
1>        with
1>        [
1>            Predict=int (__cdecl *)(void *)
1>        ]
1>c:\syy\mockcpp\include\mockcpp\chainingmockhelper.h(103) : error C2039: '()' 
: is not a member of '`global namespace''
1>c:\syy\mockcpp\include\mockcpp\chainingmockhelper.h(103) : error C2275: 
'Predict' : illegal use of this type as an expression
1>        
e:\testngpp\myprj\nppkt\nppkt\unittest\testcase\test_nppkt_pktctrl.h(53) : see 
declaration of 'Predict'
1>c:\syy\mockcpp\include\mockcpp\chainingmockhelper.h(103) : error C2275: 
'Predict' : illegal use of this type as an expression



Original issue reported on code.google.com by [email protected] on 12 Oct 2012 at 4:12

testShouldBeAbleToSpecifyAnObjectShouldKeepAlive failed due to unexpected crash

env

gcc 7.3 + linux

failed testcases

-------------------SUITE: TestMockObject2-------------------

(TestMockObject2)
..............terminate called after throwing an instance of 'mockcpp::Exception'
  what():  trying to delete an object expected keeping alive.

[ CRASHED  ] testShouldBeAbleToSpecifyAnObjectShouldKeepAlive - TestMockObject2.h:246: test crashed unexpectedly.
...

------------------SUITE: TestVirtualTable-------------------

(TestVirtualTable)
..........terminate called after throwing an instance of 'mockcpp::Exception'
  what():  trying to delete an object expected keeping alive.

[ CRASHED  ] shouldFailThrowExceptionWhileTryingToDeleteThePointerWhichWasExpectedNotTo - TestVirtualTable.h:262: test crashed unexpectedly.
....

对应关键代码

247        {
248     // TODO: Temporary disable this case on MinGW : mockcpp::Exception:  what():  trying to delete an object expected keeping alive.
249     #if !defined(__MINGW32__)
250           MockObject<Interface> mock;
251           mock.willKeepAlive();
252           TS_ASSERT_THROWS(delete (Interface*) mock, Exception);
253     #endif
254        }
255

堆栈

(gdb) bt
#0  0x00007fbaddcca4e7 in raise () from /lib64/libc.so.6
#1  0x00007fbaddccbbd8 in abort () from /lib64/libc.so.6
#2  0x00007fbade60fd95 in __gnu_cxx::__verbose_terminate_handler() () from /lib64/libstdc++.so.6
#3  0x00007fbade60db66 in ?? () from /lib64/libstdc++.so.6
#4  0x00007fbade60cb29 in ?? () from /lib64/libstdc++.so.6
#5  0x00007fbade60d498 in __gxx_personality_v0 () from /lib64/libstdc++.so.6
#6  0x00007fbade074913 in ?? () from /lib64/libgcc_s.so.1
#7  0x00007fbade074e57 in _Unwind_Resume () from /lib64/libgcc_s.so.1
#8  0x00007fbadda2762b in mockcpp::(anonymous namespace)::DestructorHolder<0u, mockcpp::(anonymous namespace)::DummyClass>::destructor(void*) () from libmockcpp-ut-TestMockObject2.so
#9  0x00007fbadd99c6c6 in TestMockObject2::testShouldBeAbleToSpecifyAnObjectShouldKeepAlive (this=0x2083fe0) at /opt/build/mockcpp/tests/ut/TestMockObject2.h:252
#10 0x00007fbadd99fa37 in TESTCASE_TestMockObject2_testShouldBeAbleToSpecifyAnObjectShouldKeepAlive::runTest (this=0x7fbaddc92e80 <testcase_instance_TestMockObject2_testShouldBeAbleToSpecifyAnObjectShouldKeepAlive>)
    at /opt/build/mockcpp/tests/ut/TestMockObject2.cpp:875
#11 0x00000000004164a9 in testngpp::TestCase::run (this=0x7fbaddc92e80 <testcase_instance_TestMockObject2_testShouldBeAbleToSpecifyAnObjectShouldKeepAlive>)
    at /opt/build/mockcpp/tests/3rdparty/testngpp/include/testngpp/internal/TestCase.h:88

原因分析

destructor 填充到虚表作为析构函数, 编译器调用析构函数,是约定析构函数不能外抛异常的,所以编译器直接省略了外层的 catch 语句,直接就走到了 std::terminate 上

建议方式

可以考虑直接测试 destructor 函数, 或者把 delete (Interface*) mock 语句封装成一个函数, 然后再断言, 即可正常工作

diff --git a/tests/ut/TestMockObject2.h b/tests/ut/TestMockObject2.h
index 5273efa..ec0ffd9 100644
--- a/tests/ut/TestMockObject2.h
+++ b/tests/ut/TestMockObject2.h
@@ -242,6 +242,11 @@ public:
       TS_ASSERT_THROWS_NOTHING(mock.verify());
    }

+   void cleanMock(MockObject<Interface>& mock)
+   {
+       delete (Interface*) mock;
+   }
+
    // willKeepAlive
    void testShouldBeAbleToSpecifyAnObjectShouldKeepAlive()
    {
@@ -249,7 +254,8 @@ public:
 #if !defined(__MINGW32__)
       MockObject<Interface> mock;
       mock.willKeepAlive();
-      TS_ASSERT_THROWS(delete (Interface*) mock, Exception);
+      // use wrapped call to prevent gcc skip catch action
+      TS_ASSERT_THROWS(cleanMock(mock), Exception);
 #endif
    }


compile fail on platform that don't have cxxabi.h

What steps will reproduce the problem?
1. compile in qnx

What is the expected output? What do you see instead?
compile failed

What version of the product are you using? On what operating system?
latest version: mockcpp-2.5-20110326.rar 
platform: qnx

Please provide any additional information below.


Original issue reported on code.google.com by [email protected] on 1 Aug 2011 at 2:08

seems can not work with gtest

What steps will reproduce the problem?
1. hg clone https://mockcpp-samples.googlecode.com/hg/ mockcpp-samples
2. add CMakeLists.txt in mockcpp-samples
   Project(Test)

SET(TOOLS_DIR ${CMAKE_SOURCE_DIR}/../tools)

INCLUDE_DIRECTORIES(${TOOLS_DIR}/gtest/include)
INCLUDE_DIRECTORIES(${TOOLS_DIR}/mockcpp/include)
INCLUDE_DIRECTORIES(${TOOLS_DIR}/3rdparty)
LINK_DIRECTORIES(${TOOLS_DIR}/gtest/lib ${TOOLS_DIR}/mockcpp/lib)

INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include)

ADD_EXECUTABLE(Test ${CMAKE_SOURCE_DIR}/test/footest.cpp 
${CMAKE_SOURCE_DIR}/src/foo.cpp)

TARGET_LINK_LIBRARIES(Test libgtest_main.a libgtest.a pthread 
libmockcpp4gtest.a)

3. compile mockcpp with cmake -DMOCKCPP_XUNIT=gtest 
-DMOCKCPP_XUNIT_HOME=/home/james/ExtDir/share/MockFramework/mockcpp-samples/tool
s/gtest 
-DCMAKE_INSTALL_PREFIX=/home/james/ExtDir/share/MockFramework/mockcpp/install ..
4. make install
4. cp install/lib/libmockcpp.a 
/home/james/ExtDir/share/MockFramework/mockcpp-samples/tools/mockpp/lib/libmockc
pp4gtest.a
5. cp -r install/include 
/home/james/ExtDir/share/MockFramework/mockcpp-samples/tools/mockpp/
6. compile mockcpp-samples
7. run test
result is :
[----------] 2 tests from TestApiHook
[ RUN      ] TestApiHook.test_api_hook_ok
[       OK ] TestApiHook.test_api_hook_ok (0 ms)
[ RUN      ] TestApiHook.test_api_hook_fail
/home/james/ExtDir/share/MockFramework/mockcpp-samples/gtest-samples/../tools/mo
ckcpp/include/mockcpp/ChainableMockMethod.h:69: Failure

=====================================
Unexpected invocation: the invocation cannot be found in allowed invoking list.
Invoked: add((int)0x1/1, (int)0x2/2)
Allowed: 
method(add)
     .expects(once())
     .invoked(0)
     .with(eq((int)0x2/2), eq((int)0x3/3))
     .will(returnValue((int)0x14/20));

=====================================

terminate called after throwing an instance of 'mockcpp::AssertionFailedError'
  what():  failed due to mockcpp exception
abandoned


What is the expected output? What do you see instead?
the result should be gtest's statistics, but the test program is exit, if there 
are some other test cases, maybe won't get invoked.

What version of the product are you using? On what operating system?
mockcpp-2.5-20110326.rar 
Linux james-VirtualBox 2.6.35-22-generic #33-Ubuntu SMP Sun Sep 19 20:34:50 UTC 
2010 i686 GNU/Linux 

Please provide any additional information below.


Original issue reported on code.google.com by [email protected] on 3 Jun 2011 at 10:13

OutBound 类构造函数初始化值列表存在乱序

: ref(val), DecoratedConstraint(constraint)

应该先构造基类,后构造成员,当前会产生编译告警

mockcpp/OutBound.h:53:7: warning: ‘mockcpp::OutBound<pcepEthrpData>::ref’ will be initialized after [-Wreorder]
      T ref;
        ^~~
include/mockcpp/OutBound.h:33:49: warning:   base ‘mockcpp::DecoratedConstraint’ [-Wreorder]
        : ref(val), DecoratedConstraint(constraint)
                      ^

include/mockcpp/OutBound.h:32:5: warning:   when initialized here [-Wreorder]
      OutBound(const T& val, Constraint* constraint = 0)
      ^~~~~~~~

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.