1

I have a function defined in a translation unit file (.cpp) something like:

    void myFunction(int option)
    {
        if (option == 0)
        {
            Meth1("arg1");
        }
        else
        {
            if (option == 1)
            {
                Meth1("arg2");
            }
            else
            {
                Meth2("arg3");
            }
        }
    }

This function has its definition in a header file but is not part of a class or struct it is just implemented in the cpp file as above. No refactoring is allowed.

Now I need to write a unit test for it to check which method is called based on the option argument. Something like in test I have

myFunction(0);

now I am testing that the Meth1 is called and its parameter has the "arg1" value.

Is it possible to write such a test ?

Clock
  • 974
  • 3
  • 17
  • 35
  • `Meth1(...)` has no return value, so I assume it must have a side-effect you can test? – Mansoor Jun 14 '21 at 14:58
  • Yes, this is possible with using macros or, if Math2 is in a library, with using a mock library. – 273K Jun 14 '21 at 15:03
  • Does this answer your question? [Mocking free function](https://stackoverflow.com/questions/28392277/mocking-free-function) – 273K Jun 14 '21 at 15:05
  • @S.M. OP mentions that the free function is defined in a non-editable source file, so mocking is probably not an option here. – Mansoor Jun 14 '21 at 15:15
  • @Mansoor Did I mention editing the source file? – 273K Jun 14 '21 at 15:42
  • @S.M. how else would you implement your mocked free function? – Mansoor Jun 14 '21 at 16:07
  • @Mansoor Meth1 and Meth2 are having no return values (are void). – Clock Jun 14 '21 at 16:28
  • @S.M. unfortunately this code can not be edit, and all those are free functions, which only got their declarations inside some headers. Will check the answer from the question you suggested, but at a first look I do not think that will have something to mock Thank you ! – Clock Jun 14 '21 at 16:32
  • @Mansoor Do you see the difference between mock library and mock free function? The duplicated question contains all possibilities, choose any, but do not say I offered modifying free functions. – 273K Jun 14 '21 at 17:31

0 Answers0