meekrosoft / fff

A testing micro framework for creating function test doubles
Other
761 stars 167 forks source link

Possibility to modify custom_fake internal variables #62

Closed oliviera9 closed 5 years ago

oliviera9 commented 5 years ago

Hello, imagine I would like to fake fgets (http://www.cplusplus.com/reference/cstdio/fgets/), so I declare: FAKE_VALUE_FUNC(char , fgets, char , int, FILE *);

Thus, I declare a custom_fake, e.g.: char custom_fgets_coolmate(char str, int n, FILE f) { char out = "mystring1"; strcpy(str, out); return out; } and assign it to the fake function.

Now, is there a convenient way to change the out variable in the custom_fake? Otherwise, whenever I would like to change the fake returning string, I would need to declare a new custom_fake and assign it as a custom_fake.

Isn't there the possibility to overcome this? Maybe it should be an option to define a global variable within the fake function which can be used within the custom_fake and can be easilly accessed in order to dynamically modify the custom_fake behavior.

Thanks!

wulfgarpro commented 5 years ago

@oliviera9, please see the section on Custom Return Value Delegate Sequences.

I understand that this isn't exactly what you're asking for, but for arbitrary changes to your out variable, you should use language features, e.g.

// MY_TEST_C
char* g_out = "initial string";

FAKE_VALUE_FUNC(char *, fgets, char*, int, FILE*);
char* custom_fgets_coolmate(char* str, int n, FILE* f)
{
    return g_out;
}

TEST_F(MyTest, CoolMate)
{
    g_out = "new string";
    fgets_fake.custom_fake = custom_fgets_coolmate;
    ASSERT_EQ(g_out, fgets(...));
}
...
oliviera9 commented 5 years ago

Thanks to you reply @wulfgarpro. This is quite similar to the solution I adopted (I just put custom fakes in a static class, and modify directly public static members which are accessed by custom fakes).

charterchap commented 5 years ago

This will allow you to make a bunch of lambda functions within your test case. You still have to have a bunch of duplicate functions but I think it will help keep things organized. The static class idea sounds like a good way to go as well. https://gist.github.com/charterchap/3113980f7ddd8c0915609492c5323ca6#file-fff_by_reference-cpp