使用 Moq 模拟 Linq to Sql EntityRef?
我的数据上下文包含一个名为 Userlog 的表,该表与表 UserProfile 具有一对多关系。
在 UserLog 类中
public UserProfile UserProfile
{
get {return this._UserProfile.Entity;}
}
在 UserProfile 类中
public EntitySet<UserLog> UserLogs
{
get{return this._UserLogs;}
}
{
set {this._UserLogs.Assign(value);
}
我如何在不更改自动生成的代码的情况下模拟(使用 Moq)UserLog.UserProfile?
我想做的是这样的:
var mockUserLog = new Mock<UserLog>();
mockUserLog.Setup(c=>c.UserProfile.FirstName).Returns("Fred");
等等,
如果我进入 Designer.cs 并使 FirstName 和 UserProfile 虚拟,我可以做到这一点,但是我想在部分类中执行此操作。
有什么想法吗?
谢谢 杰里米
My datacontext contains a table named Userlog with a one to many relationship with table UserProfile.
In class UserLog
public UserProfile UserProfile
{
get {return this._UserProfile.Entity;}
}
In class UserProfile
public EntitySet<UserLog> UserLogs
{
get{return this._UserLogs;}
}
{
set {this._UserLogs.Assign(value);
}
How would I go about mocking (using Moq) UserLog.UserProfile without changing the autogenerated code?
What I would like to do is something like:
var mockUserLog = new Mock<UserLog>();
mockUserLog.Setup(c=>c.UserProfile.FirstName).Returns("Fred");
etc
I can do this if I go into the designer.cs and make FirstName and UserProfile virtual, however I would like to do this in the partial class.
Any ideas?
Thanks
Jeremy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将方法设为虚拟的原因是因为您正在模拟直接类。解决这个问题的最佳方法是创建一个分部类(就像您建议的那样)并让该分部类继承一个接口。所以你会得到类似的东西:
设计师.cs ->公共部分类 UserLog
UserLog.cs->公共部分类 UserLog : IUserLog
IUserLog.cs->应该实现的方法(方法将由designer.cs实现)
您创建的分部类 (UserLog.cs) 仅用于实现 IUserLog。然后,IUserLog 将包含需要实现的所有方法,例如:public UserProfile UserProfile()。
完成后,您可以模拟接口而不是类。
我希望这会有所帮助,但它可能比我解释的更困难。
The reason you need to make the method virtual is because you are mocking a direct class. Best way to approach this is to make a partial class (like you suggested) and let that partial class inheret an interface. So you will have something like:
designer.cs -> public partial class UserLog
UserLog.cs -> public partial class UserLog : IUserLog
IUserLog.cs -> methods that should be implemented (methods will be implemented by the designer.cs)
The partial class you create (UserLog.cs) is only there to make it possible to implement IUserLog. IUserLog will then contain all the methods that need to be implemented, like: public UserProfile UserProfile().
Once you've done that you can mock the interface instead of the class.
I hope this helped, it might be more difficult then I explained though.