Tuesday, January 31, 2017

Mocking base class methods using Moq

While working with MVC recently, I encountered a situation where my code interacted with the OWIN context. I wanted to avoid pain in my unit tests, but didn't really have time to create an interface and wrapper for this interaction.  I had already encapsulated the OWIN context interaction to a method in my base class.  When I wrote the code I wasn't exactly sure how I was going to test it.

Turns out its pretty simple to unit test this with Moq. Just remember to set CallBase on your mock object.

//Here we are using Moq to over-ride the base class check access method which calls into the owin context.   
var controller = new Mock<UserprofileController>(_userProfileService.Object, 
    _permissionRegistry.Object, 
    _settingsRegistry.Object, 
    _logger.Object) { 
        CallBase = true 
    }; 
controller.Setup(b => b.CheckAccess(It.IsAny<string>(), It.IsAny<string[]>())).Returns(accessState);   

No comments:

Post a Comment