1

I have read the answer in this question: Using Moq to mock only some methods

My situation is similar but actually opposite or inverted at the same time. I will just use the same example/notation to illustrate it.

Suppose we are in this situation:

public CustomObect MyMethod()
{
    var lUser = GetCurrentUser();
    if (lUser.HaveAccess)
    {
        //One behavior
    }
    else 
    {
        //Other behavior
    }

    //return CustomObject
}

The user in that question wanted to mock GetCurrentUser(). In my case, I don't want to mock GetCurrentUser(), I want it to be called, and I want the rest of MyMethod() to be called.

How would I go about that?

Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
John Mayne
  • 237
  • 1
  • 3
  • 14
  • 5
    refactor your code so all the processing you want to mock is _in a different method_? – Franz Gleichmann Nov 30 '21 at 12:39
  • There are a lot of dependencies, so not sure that is feasible for the moment. – John Mayne Nov 30 '21 at 12:43
  • If you need to mock part of the code, it is likely a good reason to refactor it, avoiding complex code. – Cleptus Nov 30 '21 at 12:47
  • 1
    `There are a lot of dependencies` - in that case, a different recommendation: _refactor ASAP_ before even thinking about doing anything else. – Franz Gleichmann Nov 30 '21 at 12:47
  • I don't understand the question. Sometimes we have to change code if we want to be able to mock something. But you don't want to mock anything. In that case you don't have to do anything. If a test executes `MyMethod` nothing will be mocked. The code already does what you want. – Scott Hannen Nov 30 '21 at 15:36

1 Answers1

1

Without a lot of complexity you can break the dependencies to mock your indepent tests. Of course you upload a pseudo code, so I answer based on that pseudo code, but if you need more help, please comment and I will glade to update my answer.

public CustomObect MyMethod()
{
    return CheckAccess(GetCurrentUser());
}

public CustomObject  CheckAccess(lUserType lUser) {
if (lUser.HaveAccess)
    {
        //One behavior
    }
    else 
    {
        //Other behavior
    }
    //return CustomObject (assuming you need here)
}

Even more you can consider make every "behavior" in a different method so you can test the "behavior" without the condition.

Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116