将google mock matcher描述为std :: string

时间:2013-11-13 11:53:37

标签: c++ googlemock

我的问题(针对住院病人)

鉴于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中找到任何这样的功能,必须自己编写。

1 个答案:

答案 0 :(得分: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