Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq a static method in static class

Tags:

moq

 public Product GetbyID(int id)
    {            
            try
            {
               //mycode Product p=..........

            }
            catch (DataAccessException ex)
            {
                throw new BusinessException(ex.ErrorCode);
            }
            catch (Exception ex)
            {
                BusinessExceptionHandler.LogException(ex);
            }

        return p;
    }

Given above is a code snippet that i need to write test cases. here LogException(ex); is a static method in static class BusinessExceptionHandler

I have reference to Moq frame work 2.6.1014.1

How can I Moq the method BusinessExceptionHandler.LogException

I do prefer a mocking mechanism that don't need any change in method GetbyID

like image 425
Kuttan Sujith Avatar asked Jan 29 '12 11:01

Kuttan Sujith


Video Answer


1 Answers

Moq doesn't allow the mocking of static methods so you will probably need to change the working of the static method. One option is to have the static method call an instance method of a dependency. So you'll create a "Logger" class with a Log method and add a static Logger field / property (BusinessExceptionHandler.Logger) to your static class. In the real-world scenario you can populate BusinessExceptionHandler.Logger with a standard Logger instance, using it as a Singleton. For testing, inject a Mock into the BusinessExceptionHandler.Logger and set up your expectations and verify against the mock.

like image 91
BlackWasp Avatar answered Oct 13 '22 00:10

BlackWasp