开发者

Moq Linq-to-SQL readonly property

开发者 https://www.devze.com 2022-12-12 14:27 出处:网络
I have a table aspnet_User in my model(dbml file) where I have a property UserName which is ReadOnly. I thought I could do this.

I have a table aspnet_User in my model(dbml file) where I have a property UserName which is ReadOnly. I thought I could do this.

var mockAsp_NetUser = new Mock<aspnet_User>();
mockAsp_NetUser.SetupGet(au => au.UserName).Returns("JohnDoe");

But then I get an exception: Invalid setup on a non-overridable member.

An easy solution would be to set the ReadOnly property for UserName to false in the model designer. But this might be a hack. Is th开发者_如何学Cere a more "correct" way?


You can't mock what is not either virtual or abstract.

If you are trying to unit test your code, a better approach would be to define an IUser class and let your code work against that interface.


Just an addition to Marks answer:

In the DBML you can set that the property should have "Instance Modifier" = "virtual". By default its set to (None).

For your example that means: In the DBML Designer, select the Member "UserName" and in the Properties you will find "Instance Modifier".

Once set to virtual your code will work.

0

精彩评论

暂无评论...
验证码 换一张
取 消