Mocking free function

前端 未结 4 529
我在风中等你
我在风中等你 2020-11-27 06:10

I am stuck in a problem and can\'t seem to find the solution.

I am using VS2005 SP1 for compiling the code.

I have a global function:

A* foo(         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 06:48

    There are 2 options:

    If you insist on using gmock, there's an "extension" for global mocking from apriorit: https://github.com/apriorit/gmock-global

    It's rather limited, though - or at least I couldn't figure out in 5 minutes how to have side effects on a mocked call.

    If you're willing to switch from gmock, then hippomocks has a very neat way of doing what you want.

    Here's an example for mocking fopen, fclose and fgets for testing a member function which reads from a file using cstdio (streams are very inefficient):

    TEST_CASE("Multi entry") {
        std::vector files{"Hello.mp3", "World.mp3"};
        size_t entry_idx = 0;
        MockRepository mocks;
        mocks.OnCallFunc(fopen).Return(reinterpret_cast(1));
        mocks.OnCallFunc(fgets).Do(
            [&](char * buf, int n, FILE * f)->char *{ 
                if (entry_idx < files.size())
                {
                    strcpy(buf, files[entry_idx++].c_str());
                    return buf;
                }
                else
                    return 0;
                }
            );
        mocks.OnCallFunc(fclose).Return(0);
    
        FileExplorer file_explorer;
        for (const auto &entry: files)
            REQUIRE_THAT(file_explorer.next_file_name(), Equals(entry.c_str()));
        REQUIRE_THAT(file_explorer.next_file_name(), Equals(""));
    }
    

    Where the function under test looks like this:

    string FileExplorer::next_file_name() {
        char entry[255];
        if (fgets((char *)entry, 255, _sorted_entries_in_dir) == NULL)
            return string();
        _current_idx++;
        if (_current_idx == _line_offsets.size())
            _line_offsets.push_back(static_cast(char_traits::length(entry)) + _line_offsets.back());
        return string(entry);
    } 
    

    I'm using catch2 as the testing framework here, but I think hippomocks would work with Google's Testing framework as well (I recommend catch2, by the way, really easy to work with).

提交回复
热议问题