Gmock - matching structures

后端 未结 5 1833
误落风尘
误落风尘 2021-02-07 16:10

How can I match value of an element in a union for an input argument e.g - if I mock a method with the following signatiure -

    struct SomeStruct
    {   
           


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-07 16:49

    Google provides some good documentation on using gmock, full of example code. I highly recommend checking it out:

    https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#using-matchers

    As you pointed out, a default equality operator (==) isn't automatically created for class types (including PODs). Since this operator is used by gmock when matching parameters, you would need to explicitly define it in order to use the type as you would any other type (as seen below):

        // Assumes `SomeMethod` is mocked in `MockedObject`
        MockedObject foo;
        SomeStruct expectedValue { 1, 2 };
    
        EXPECT_CALL(foo, SomeMethod(expectedValue));
    

    So, the most straightforward way of dealing with this is to define an equality operator for the struct:

    struct SomeStruct
    {   
        int data1;
        int data2; 
    
        bool operator==(const SomeStruct& rhs) const
        {
            return data1 == rhs.data1
                && data2 == rhs.data2;
        }
    };
    

    If you don't want to go that route, you can consider using the Field matcher to match the parameter based on the values of its member variables. (If a test is interested in comparing equality between instances of the struct, though, it's a good indication that other code will be interested as well. So it'd likely be worthwhile to just define an operator== and be done with it.)

提交回复
热议问题