How do I mock a method call within a method I want to test using NUnit?
I'm trying to unit test a method and poke fun at calling the method 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 call to the GoToMainMenu () function as this is for navigation only and I get the exception thrown here when I try to run my test.
I've tried using 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.
I spent a lot of time on various ways to make this work and also tried Rhino Mocks, but couldn't figure out how to mock this challenge. Can anyone help with this? I have not tried Moq, but I suspected it was similar to Rhino Mocks.
source to share
In your current setup, this is what you are trying to do, not possible. Fixed a bit:
- start using the stable version of Rhino (e.g. 3.6). Better yet, upgrade to Moq, which is a new framework.
- make a
GoToMainMenu
methodvirtual
(and at leastprotected
)
Then your test (Rhino 3.6) should look like this:
var mock = MockRepository.GenerateMock<LoginViewModel>();
Assert.AreEqual(true, mock.LogUserIn("aHashedPassword"));
A few things to note here. Any non-virtual method will use your original implementation (for example LogUserIn
). On the other hand, each virtual method will be replaced by RhinoMocks with a default implementation (do nothing), which should be enough to pass the test. The same test in Moq:
var mock = new Mock<LoginViewModel>();
Assert.AreEqual(true, mock.Object.LogUserIn("aHashedPassword"));
The way it works (need to have methods virtual
) is that when you create a layout, both Rhino and Moq will be generated in the memory assembly and create a new type there based on your type (in your case LoginViewModel
). The derived type (mock) can then replace any method of the original type given it virtual
(standard C # mechanism) or the type is an interface - then the mock simply implements the interface.
source to share