This is my simple code.
public class Permission
{
public string Name { get; set; }
public bool IsEnable { get; set; }
}
public class User
{
public virtual List<Permission> Permissions { get; set; }
public bool ContainPermission(string permissionName)
{
var result = Permissions.Where(p => p.Name == permissionName && p.IsEnable).FirstOrDefault();
return result != null;
}
}
And I want to test method ContainPermission.
I am using Moq and write this code:
[TestClass]
public class UserPermissionTest
{
[TestMethod]
public void UserContainPermission_WhenPermissionEnable_ReturnTrue()
{
var mockUser = new Mock<User>();
mockUser.SetupGet(p => p.Permissions).Returns(
() => new List<Permission>
{
new Permission {Name = "Name", IsEnable = true}
});
var user = mockUser.Object;
var isContainPermission = user.ContainPermission("Name");
Assert.IsTrue(isContainPermission);
}
}
It works! Test method pass. But I decided to check it one’s more. I changed method ContainPermission:
public bool ContainPermission(string permissionName)
{
Permissions.Clear();
var result = Permissions.Where(p => p.Name == permissionName && p.IsEnable).FirstOrDefault();
return result != null;
}
And my test method pass too! I don’t understand why? What’s wrong is my code?
Because of the following line, any time you ask for permissions you will always get a result:
You can test that you get the required result when the collection is empty by writing another test as follows: