Search code examples
c#unit-testingmoqprivate-methods

Moq c# private method to throw an exception


Given this class:

public class MyClass 
{  
     private void MyMethod()  
     {  
         //...
     }  

     public void Execute()
     {  
        try
        {
             //...  
             MyMethod();  
             //... 
        }  
        catch(Exception e)  
        {  
            ...  
        }   
     }  
}

How can I Mock MyMethod to throw an OutOfmemoryException ?

EDIT 1:

Given the next situation where MyMethod loads some data from database, and some unpredicted error occurs, MyMethod will throw an exception. I want to be able to unit test that situation. In my case the catch clause from execute method.


Solution

  • I don't use Moq, so it's possible that there's some way you can do it - but I'd argue that if you need to, you're doing mocking wrong.

    You should usually be mocking dependencies - and you can't be depending on their private members from the class you're trying to test, can you? Typically I'd mock an interface - occasionally it can be useful to mock a class, but I typically don't. If you're calling into some dependency and you want the result of that call to be an OutOfMemoryException, just make that public call throw the exception.

    If you feel you've got a good reason to want to mock a private method, please give more details about your context.