2

我的问题(住院病人)

给定一个 google-mock 匹配器,我想将它描述为一个字符串。例如:

std::string description = DescribeMatcher(Ge(0)) // puts "size is > 0" in the string

有人知道这样做的简单方法吗?在 googlemock 文档中没有找到任何内容。我自己是这样做的:

template<typename T, typename S>
std::string DescribeMatcher(S matcher)
{
    Matcher<T> matcherCast = matcher;
    std::ostringstream os;
    matcherCast.DescribeTo(&os);
    return os.str();
}

背景

我想编写自己的匹配器,它基于不同的匹配器。我的匹配器匹配一个字符串,该字符串表示具有指定大小的文件的名称。

MATCHER_P(FileSizeIs, sizeMatcher, std::string("File size ") + DescribeMatcher(sizeMatcher))
{
    auto fileSize = fs::file_size(arg);
    return ExplainMatchResult(sizeMatcher, fileSize, result_listener);
}

以下是它的用法示例:

EXPECT_THAT(someFileName, FileSizeIs(Ge(100)); // the size of the file is at-least 100 bytes
EXPECT_THAT(someFileName, FileSizeIs(AllOf(Ge(200), Le(1000)); // the size of the file is between 200 and 1000 bytes

问题出在 MATCHER_P 宏的最后一个参数中。我希望 的描述FileSizeIs基于 的描述sizeMatcher。但是,我在googlemock中没有找到任何这样的功能,只好自己写。

4

1 回答 1

2

我在创建嵌套匹配器时遇到了类似的问题。我的解决方案使用 MatcherInterface 而不是 MATCHER_P。对于您的情况,这将类似于:

template <typename InternalMatcher>
class FileSizeIsMatcher : public MatcherInterface<fs::path> {
public:
    FileSizeIsMatcher(InternalMatcher internalMatcher)
            : mInternalMatcher(SafeMatcherCast<std::uintmax_t>(internalMatcher))
    {
    }
    bool MatchAndExplain(fs::path arg, MatchResultListener* listener) const override {
        auto fileSize = fs::file_size(arg);
        *listener << "whose size is " << PrintToString(fileSize) << " ";
        return mInternalMatcher.MatchAndExplain(fileSize, listener);
    }

    void DescribeTo(std::ostream* os) const override {
        *os << "file whose size ";
        mInternalMatcher.DescribeTo(os);
    }

    void DescribeNegationTo(std::ostream* os) const override {
        *os << "file whose size ";
        mInternalMatcher.DescribeNegationTo(os);
    }
private:
    Matcher<std::uintmax_t> mInternalMatcher;
};

template <typename InternalMatcher>
Matcher<fs::path> FileSizeIs(InternalMatcher m) {
    return MakeMatcher(new FileSizeIsMatcher<InternalMatcher>(m));
};

例子:

TEST_F(DetectorPlacementControllerTests, TmpTest) {
    EXPECT_THAT("myFile.txt", FileSizeIs(Lt(100ul)));
}

给出输出:

Value of: "myFile.txt"
Expected: file whose size is < 100
Actual: "myFile.txt" (of type char [11]), whose size is 123 
于 2019-12-19T13:07:32.483 回答