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

ネストされたマッチャーを作成する際にも同様の問題がありました。私のソリューションでは、MATCHER_P の代わりに MatcherInterface を使用しています。あなたの場合、これは次のようになります。

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 に答える