fake/mock nonvirtual C++ methods

后端 未结 8 1655
谎友^
谎友^ 2020-12-13 19:32

It known that in C++ mocking/faking nonvirtual methods for testing is hard. For example, cookbook of googlemock has two suggestion - both mean to modify original source code

8条回答
  •  执笔经年
    2020-12-13 20:04

    @zaharpopov you can use Typemock IsolatorPP to create mocks of non-virtual class and methods without changing your code (or legacy code). for example if you have a non-virtual class called MyClass:

    class MyClass
    {
     public:
       int GetResult() { return -1; }
    }
    

    you can mock it with typemock like so:

    MyClass* fakeMyClass = FAKE();
    WHEN_CALLED(fakeMyClass->GetResult()).Return(10);
    

    By the way the classes or methods that you want to test can also be private as typemock can mock them too, for example:

    class MyClass
    {
    private:
       int PrivateMethod() { return -1; }
    }
    
    
    MyClass* myClass =  new MyClass();
    
    PRIVATE_WHEN_CALLED(myClass, PrivateMethod).Return(1);
    

    for more information go here.

提交回复
热议问题