[英]How do I mock a method call inside the method I want to test using NUnit?
I'm trying to unit test a method and mock the method call inside it: 我正在尝试对方法进行单元测试并模拟其中的方法调用:
class LoginViewModel
{
public bool LogUserIn(string hashedPassword)
{
//Code
if (loginSuccessful)
{
GoToMainMenu(); // I WANT TO MOCK THIS CALL.
return true;
}
return false;
}
}
so I want to mock the GoToMainMenu() function call, as this is only for navigation and I get an exception thrown here when I try to run my test. 所以我想模拟GoToMainMenu()函数调用,因为这只是用于导航,当我尝试运行我的测试时,我得到一个异常抛出。
I've tried using NUnit.Mocks: 我尝试过使用NUnit.Mocks:
[Test]
public void Log_User_In_Will_Return_True()
{
DynamicMock mockView = new DynamicMock(typeof(LoginViewModel));
mockView.ExpectAndReturn("GoToMainMenu", null);
LoginViewModel loginVM = (LoginViewModel)mockView.MockInstance; //ArgumentException
Assert.AreEqual(true, loginVM.LogUserIn("aHashedPassword"));
}
But this gives me an ArgumentException. 但这给了我一个ArgumentException。
I've spent a lot of time trying different ways to make this work and have also tried Rhino Mocks but couldn't get my head around how to mock this call. 我花了很多时间尝试不同的方法来完成这项工作,并且还尝试过Rhino Mocks但是无法理解如何模拟这个调用。 Can anyone help with this?
有人能帮忙吗? I haven't tried Moq but suspected it to be similar to Rhino Mocks.
我没有尝试过Moq,但怀疑它与Rhino Mocks类似。
In your current setup this what you're trying to do is impossible. 在您当前的设置中,您尝试做的事情是不可能的。 Few things to fix:
几件事情无法解决:
GoToMainMenu
method virtual
(and at least protected
) GoToMainMenu
方法virtual
(至少protected
) Your test then (Rhino 3.6) should look like this: 那么你的测试(Rhino 3.6)应如下所示:
var mock = MockRepository.GenerateMock<LoginViewModel>();
Assert.AreEqual(true, mock.LogUserIn("aHashedPassword"));
Few things to note here. 这里有几点需要注意。 Any non-virtual method called will use your original implementation (like
LogUserIn
). 调用的任何非虚方法都将使用您的原始实现(如
LogUserIn
)。 Every virtual method on the other hand will be replaced by RhinoMocks with default ( do nothing ) implementation, which should be enough to make test pass. 另一方面,每个虚拟方法都将由具有默认( 不执行任何 )实现的RhinoMocks替换,这应该足以使测试通过。 The same test in Moq:
在Moq进行相同的测试:
var mock = new Mock<LoginViewModel>();
Assert.AreEqual(true, mock.Object.LogUserIn("aHashedPassword"));
The way it works like this (need to have virtual
methods) is because when creating a mock, both Rhino and Moq will generate in memory assembly and create new type there, deriving from your type (in your case, LoginViewModel
). 它的工作方式(需要有
virtual
方法)是因为在创建模拟时,Rhino和Moq都会在内存中生成程序集并在那里创建新类型,从你的类型派生(在你的情况下,是LoginViewModel
)。 Derived type (mock) can then replace any method of original type given it's virtual
(standard C# mechanism) or type is interface - then the mock simply implements the interface. 派生类型(模拟)可以替换任何原始类型的方法,因为它是
virtual
(标准C#机制)或类型是接口 - 然后模拟只是实现接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.