为什么 Moq-mocked 方法返回 null?
当我尝试使用模拟的 GetProfileFromUserName
方法时,它返回 null
。名为 GetEmail
的类似方法也有效。
这是用于检索个人资料的代码,但不起作用:
mockUserRepository.Setup(gp => gp.GetProfileFromUserName(userProfile.UserName))
.Returns(new Profile { ProfileID = userProfile.ProfileID });
这是用于检索电子邮件的代码,但不起作用。
mockUserRepository.Setup(em => em.GetEmail(new MockIdentity("JohnDoe").Name))
.Returns("[email protected]");
这是模拟调用并返回 null 而不是配置文件的方法的片段:
public ActionResult ShowProfile()
{
var profile = _userRepository.GetProfileFromUserName(User.Identity.Name);
我做错了什么?
如果我将 GetProfileFromUserName 中的 userProfile.UserName 替换为 It.IsAny();
When I try to use my mocked GetProfileFromUserName
method, it returns null
. A similar method named GetEmail
works.
This is the code for retrieving the profile, which doesn't work:
mockUserRepository.Setup(gp => gp.GetProfileFromUserName(userProfile.UserName))
.Returns(new Profile { ProfileID = userProfile.ProfileID });
And this is the code for retrieving the email, which works.
mockUserRepository.Setup(em => em.GetEmail(new MockIdentity("JohnDoe").Name))
.Returns("[email protected]");
And this is a snippet of the method the mock calls and returns null on instead of a profile:
public ActionResult ShowProfile()
{
var profile = _userRepository.GetProfileFromUserName(User.Identity.Name);
What am i doing wrong?
If i replace the userProfile.UserName in the GetProfileFromUserName to It.IsAny();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果它返回 null,则意味着您的
Setup
与实际调用不匹配。检查userProfile.UserName
在设置行是否包含正确的值。此外,要检测不匹配的调用,请使用
MockBehavior.Strict
选项创建mockUserRepository
。希望这有帮助。
If it returns null, it means that your
Setup
didn't match the actual call. Check that theuserProfile.UserName
contains the correct value at the Setup line.Also, to detect the unmatched calls create your
mockUserRepository
with theMockBehavior.Strict
option.Hope this helps.
就我而言,错误是使用错误的签名初始化对象,即使代码已编译:
错误(参数类型为int):
正确 (参数类型为int?):
模拟方法的签名:
In my case the mistake was initializing the object with a wrong signature even the code was compiled:
Wrong (The parameter type is int):
Correct (The parameter type is int?):
Mocked method's signature:
对于任何试图返回在测试设置(“Arrange”)时不存在的对象的人,解决方案是使用委托(Func<>)重载:
For anybody who is trying to return an object, that does not exist at the time of the test setup ("Arrange"), the solution is to use the delegate (Func<>) overload:
我有一个类类型对象作为参数传递给 moq 方法。所以我用了
I had a class type object passed as parameter to the moq method. So I used