Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the MOQ library to mock an ENum

I am having an issue using the Moq library to mock an Enum within my project. I am trying to test a class and one of the methods accepts an ENum. Is there any way to do this?

Here is the Enum I am trying to mock:

public enum PermissionType
{
   Create = 0,
   Read = 1,
   Update = 2,
   Delete = 3,
}

Here is the code I am trying to use to create the mock:

 private static Mock<PermissionService> GetMockPermissionService(bool hasPermissions)
 {
    var mockPermissionService = new Mock<PermissionService>();

    mockPermissionService.Setup(x => x.HasPermission(It.IsAny<string>(), 
                      **It.IsAny<PermissionType>()**)).Returns(hasPermissions);

    return mockPermissionService;
 }

This is the error I receive:

System.ArgumentException: Invalid setup on a non-overridable member: x => x.HasPermission(It.IsAny(), It.IsAny())

I have also tried:

mockPermissionService.Setup(x => x.HasPermission(It.IsAny<string>(), 
                          **It.IsAny<int>()**)).Returns(hasPermissions);

mockPermissionService.Setup(x => x.HasPermission(It.IsAny<string>(), 
                          **PermissionType.Read**)).Returns(hasPermissions);

Any help would be appreciated...

like image 295
Pat Avatar asked Oct 08 '09 20:10

Pat


1 Answers

This error means that your HasPermission method on PermissionService must be virtual, like so:

public virtual bool HasPermission(string name, PermissionType type)
{
   // logic
}
like image 186
Chris Missal Avatar answered Nov 03 '22 07:11

Chris Missal