GenerateMockClass.refscript

This page describes the GenerateMockClass RefactorScript shipped with VisualGDB.

Overview

This script generates a mock class for the given class, or an explicitly selected group of methods.
It uses the GoogleMock syntax, however it can be easily adjusted to generate any other syntax.

You can use it by selecting a class in Code Explorer -> Outline, or via Smart Tags in the code editor.

Script

[Main, Description("Generate a mock class"), SuggestFor(Record)]
generator GenerateMockClass(Array classOrMethods)

{
    if ((classOrMethods.Length == 1) && (classOrMethods.First is Record))
        DoGenerateMockClass(classOrMethods.First, classOrMethods.First.Methods, true);
    else
        DoGenerateMockClass(classOrMethods.First.ContainingType, classOrMethods, false);
}

function WrapIfContainsCommas(string str)
{
    if (str.Contains(","))
        return "(" + str + ")";
    else
        return str;
}

generator DoGenerateMockClass(Record class, Array methods, bool publicOnly)
{
>class Mock$class.ShortName
>{
>public:
    foreach(method in methods)
    {
        if (publicOnly && (method.Access != "public"))
            continue;

        if (method.IsImplicit || method.IsConstructor ||
            method.IsDestructor || method.IsOperator)
            continue;

        set type = WrapIfContainsCommas(method.ReturnType.Literal);
>>    MOCK_METHOD($type, $method.ShortName, (
        foreach(arg in method.Arguments)
        {
            set type = WrapIfContainsCommas(arg.Type.Literal);
>>$type
            if (!arg.IsLast)
>>, 
        }
>>)
        if (method.IsConst)
            >>, (const)
>);
    }
>};
}

Sample Input

class MockDemo
{
public:
    MockDemo(int x);
    int Subtract(int x, int y);
    double Sqrt(double x);
    int Square(int arg);
};

Sample Output

class MockMockDemo
{
public:
    MOCK_METHOD(int, Subtract, (intint));
    MOCK_METHOD(double, Sqrt, (double));
    MOCK_METHOD(int, Square, (int));
};
A detailed reference on RefactorScript syntax and data model is available here.
See this page for a full list of RefactorScripts shipped with VisualGDB.