仅模拟 C# 中函数的一部分?
Mock only a part of a function in C#?
我已经阅读了这个问题的答案:Using Moq to mock only some methods
我的情况类似,但实际上同时相反或相反。我将使用相同的 example/notation 来说明它。
假设我们处于这种情况:
public CustomObect MyMethod()
{
var lUser = GetCurrentUser();
if (lUser.HaveAccess)
{
//One behavior
}
else
{
//Other behavior
}
//return CustomObject
}
该问题中的用户想要模拟 GetCurrentUser()
。就我而言,我不想模拟 GetCurrentUser()
,我希望它被调用,我希望 MyMethod()
的其余部分被调用。
我该怎么做?
没有太多的复杂性,您可以打破依赖性来模拟您的独立测试。当然你上传了一个伪代码,所以我根据那个伪代码回答,但是如果你需要更多帮助,请评论,我很乐意更新我的答案。
public CustomObect MyMethod()
{
return CheckAccess(GetCurrentUser());
}
public CustomObject CheckAccess(lUserType lUser) {
if (lUser.HaveAccess)
{
//One behavior
}
else
{
//Other behavior
}
//return CustomObject (assuming you need here)
}
甚至你可以考虑用不同的方法让每个“行为”,这样你就可以在没有条件的情况下测试“行为”。
我已经阅读了这个问题的答案:Using Moq to mock only some methods
我的情况类似,但实际上同时相反或相反。我将使用相同的 example/notation 来说明它。
假设我们处于这种情况:
public CustomObect MyMethod()
{
var lUser = GetCurrentUser();
if (lUser.HaveAccess)
{
//One behavior
}
else
{
//Other behavior
}
//return CustomObject
}
该问题中的用户想要模拟 GetCurrentUser()
。就我而言,我不想模拟 GetCurrentUser()
,我希望它被调用,我希望 MyMethod()
的其余部分被调用。
我该怎么做?
没有太多的复杂性,您可以打破依赖性来模拟您的独立测试。当然你上传了一个伪代码,所以我根据那个伪代码回答,但是如果你需要更多帮助,请评论,我很乐意更新我的答案。
public CustomObect MyMethod()
{
return CheckAccess(GetCurrentUser());
}
public CustomObject CheckAccess(lUserType lUser) {
if (lUser.HaveAccess)
{
//One behavior
}
else
{
//Other behavior
}
//return CustomObject (assuming you need here)
}
甚至你可以考虑用不同的方法让每个“行为”,这样你就可以在没有条件的情况下测试“行为”。