如何对此进行单元测试
我正在尝试为我的一个服务层编写第一个单元测试。我正在使用 nunit 和 moq (最新版本)。
我有一个回购协议,但我会嘲笑它,这没问题。
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;
}
这就是我所拥有的。
现在让我困扰的是这个许可。我不知道该怎么做。我不确定是否必须创建一个包含 id 的permissionLevels 的用户对象。
我不确定我是否可以模拟它,但我对此表示怀疑,因为它是私人的。
第二个问题是我不确定如何创建一个“id”,因为“id”位于具有私有集的域类中,因为这是 nhibernate 使用的标准。
所以我不知道如何解决这个问题。
I am trying to write my first unit test for one of my service layers. I am using nunit and moq (latest versions).
I 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,假设您正在模拟 GetUserByEmail,您可以让它返回包含一组示例权限的用户。
Yes, assuming you're mocking GetUserByEmail, you can have it return a user that contains a sample set of permissions.
我会将 Repo.GetUserByEmail 方法包装在一个单独的类中,并将其注入到您的类中。类似这样:
因此,您可以存根 UserProvider 类,并始终完全控制测试中的用户。
请记住还要测试 UserProvider 类;o)
问候,
莫滕
I would wrap the Repo.GetUserByEmail method in a separate class and inject this into your class. Something like this:
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