17

I have a function which uses out parameters. How can I mock this function?

My function is:

GetProperties(out string name, out string path, out string extension);

In my original code, I am doing this:

string Name;
string Path;
string Extension;
MyObject.GetProperties(out Name, out Path, out Extension);

Now, how I can mock this?

LHM
  • 721
  • 12
  • 31
fhnaseer
  • 7,159
  • 16
  • 60
  • 112
  • 1
    Similar question http://stackoverflow.com/questions/1068095/assigning-out-ref-parameters-in-moq – Alex Jul 19 '12 at 07:37
  • didnt get it, can u write me the code, mocking a function returning a string is simple, mockObject.Setup(f => f.SomeMethod()).Returns("string"); but dont know about out parameters, – fhnaseer Jul 19 '12 at 07:40

1 Answers1

25

You should assign out variable's value before calling the method like this:

string Name = "name";
string Path = "path";
string Extension = "extension";
mock.Setup(item => item.GetProperties(out Name, out Path, out Extension))
    .Returns(someReturnValue);

Although I would prefer returning these values in your return type, instead of using so many out parameters.

Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
  • function is of a COM object written in c++, so thats why there are so many out parameters, i thought that CallBack can be used in this, but dont know how, – fhnaseer Jul 19 '12 at 07:46
  • If you have to mock just the return values of the out parameters it should work fine, you wouldn't need the Callback. – Ufuk Hacıoğulları Jul 19 '12 at 07:58
  • 1
    @FaisalHafeez You shouldn't mock a COM object unless you designed it. You're getting no design feedback. Even if you did design it, if your tests aren't going to influence the design of the method, there's not much point in mocking it. You're probably better off wrapping the call inside a very simple class and not testing that class. You might find this useful: https://www.youtube.com/watch?v=R9FOchgTtLM. – jpmc26 Oct 26 '13 at 01:06