I am trying to write my first unit test for one of my service layers. I am using nunit and moq (latest versions).
开发者_如何学GoI have a repo but I will mock that out that is no problem.
public void Create(string email, int id)
{
User user = Repo.GetUserByEmail(email); // mock this out. and return a mocked user.
if user != null)
{
// check permission
var clearence = GetPermissions(user, PermissionTypes.Add, id);
// some other stuff
}
}
private static List<Permissions> GetPermissions(User user, PermissionTypes PermissionNeeded, int id)
{
List<PermissionLevel> clearence = user.PermissionLevels.Where(u => u.id == id &&
(u.Permission.Name == PermissionNeeded || u.Permission.Name == PermissionTypes.Owner)).ToList();
return clearence;
}
So that is what I have.
Now what is getting me is this clearance. I am not sure how to do it. I am not sure if I have to make a user object that has a permissionLevels in it that contains a id.
I am not sure if I could mock it up but I doubt it since it is private.
The second problem is I am not sure how to create an "id" as the "id" is in a domain class that has a private set because well that was the standard used for nhibernate.
So I am not sure how to get around that.
Yes, assuming you're mocking GetUserByEmail, you can have it return a user that contains a sample set of permissions.
I would wrap the Repo.GetUserByEmail method in a separate class and inject this into your class. Something like this:
public class YourClass
{
private readonly UserProvider _userProvider;
public TestedClass(UserProvider userProvider)
{
_userProvider = userProvider;
}
public void Create(string email, int id)
{
User user = _userProvider.GetUser(email, PermissionTypes.Add, id); // mock this out. and return a mocked user.
if (user != null)
{
// check permission
var clearence = GetPermissions(user, PermissionTypes.Add, id);
// some other stuff
}
}
}
public class UserProvider
{
public User GetUser(string email, PermissionTypes.Add, id)
{
return Repo.GetUserByEmail(email);
}
}
Thus, you can stub the UserProvider class and always have full control over the user in the test.
Remember to test the UserProvider class as well ;o)
Regards, Morten
精彩评论