What is the right way to mock void functions in RhinoMocks? - c#

I have this interface that returns void in some functions that I would like to mock and wonder what is the correct way of doing so. As of now I have the following:
var mocks = new MockRepository();
var mockedInterface = mocks.CreateMock<IMyInterface>();
Expect.Call(mockedInterface.FunctionThatReturn(param1, param2)).Return(Something);
mockedInterface.FunctionReturningVoid(param3, param4);
mocks.ReplayAll();
// Some assert and other stuff
mocks.VerifyAll();
Is that the right way of doing it? I think it looks weird since you're not handling the two functions the same way. What I would like to write is:
var mocks = new MockRepository();
var mockedInterface = mocks.CreateMock<IMyInterface>();
Expect.Call(mockedInterface.FunctionThatReturn(param1, param2)).Return(Something);
Expect.Call(mockedInterface.FunctionReturningVoid(param3, param4)); // This doesn't work.
mocks.ReplayAll();
// Some assert and other stuff
mocks.VerifyAll();
But that doesn't work on row 4. I found some blog that says you can use lambdas (or delegate) like
Expect.Call(() => mockedInterface.FunctionReturningVoid(param3, param4)); // This doesn't work.
But that doesn't seem to work either for me. Having the Expect.Call makes it easy to identify mocked functions and that is why I want it. The compile error I get is: "Cannot convert lambda expression to type 'object' because it is not a delegate type".
So how should it be done?
UPDATE: Added compile error information.

I prefer the AAA (arrange/act/assert) syntax instead of record/replay. It's more straightforward and makes the tests easier to read. What you'll want to do is:
// arrange
var mock = MockRepository.GenerateMock<IMyInterface>
mock.Expect(i => i.FunctionThatReturnSomething(param1, param2)).Return("hello");
mock.Expect(i => i.FunctionThatReturnVoid(param3, param4));
// set up other stuff for your code (like whatever code depends on IMyInterface)
var foo = new Foo(mock);
// act
foo.DoSomething();
// assert
mock.VerifyAll();

For void methods I use anonymous delegates:
Expect.Call(delegate { mockedInterface.FunctionReturningVoid(param3, param4); })
BTW: I like Record-Playback syntax for replaying and verifying expectations
http://www.ayende.com/Wiki/(S(j2mgwqzgkqghrs55wp2cwi45))/Comparison+of+different+Rhino+Mocks+syntaxes.ashx

Not sure how to test void method in AAA pattern, I was also having trouble mocking void. However, in the past, I use the Record and Playback style, and that should work.
Example:
private MockRepository m_mocks = new MockRepository();
private IXGateManager xGateManager = m_mocks.DynamicMock<IXGateManager>();
using (m_mocks.Record())
{
xGateManager.SendXGateMessage(null, null);
LastCall.IgnoreArguments().Repeat.Once();
}
using (m_mocks.Playback())
{
//... execute your test
}

Related

Moq Test error Null on Service Layer

How can the following test be corrected to work?
[TestMethod()]
public void GetEmployeeProductivityTest()
{
var mockHR = new Mock<IRepository<Employee>>();
var mockCMS = new Mock<ICMS_Repository>();
mockCMS.Setup(repos => repos.FindEmployeeByUsername(It.IsAny<string>())).Verifiable();
Employee newEmp = new Employee();
newEmp.User_Name = "testName";
var service = new EmployeeService(mockHR.Object,mockCMS.Object);
var createResult = service.GetEmployeeByUserName(newEmp);
Assert.AreEqual(newEmp, createResult);
mockCMS.VerifyAll();
}
I get the following:
Assert.AreEqual failed. Expected:<Employee>. Actual:<(null)>.
As Requested this is the GetEmployeeByUserName() function being called:
public Employee GetEmployeeByUserName(Employee employee)
{
return _employeeRespository.Find().ByUserName(employee); <------(Using Strict: Gives me the following: All invocations on the mock must have a corresponding setup.)
}
Since you edited your question to show the behaviour of the GetEmployeeByUserName, it's now easy to explain why your test was failing.
mockCMS.Setup(repos => repos.FindEmployeeByUsername(It.IsAny<string>()))
Here you set up an expectation that the FindEmployeeByUsername(string) overload would be called, but then you go on to use the FindEmployeeByUsername(Employee) overload. Moq setups are for specific overloads so when the method is called the mocked service finds no matching setup. If there is no matching setup, the mock either returns the default value for the Employee type (null), or throws an exception, depending on which MockBehavior you chose.
In your updated test, you fixed this by setting up the overload that you actually use.
mockCMS.Setup(repos => repos.FindEmployeeByUsername(It.IsAny<Employee>()))
With simple methods like your GetEmployeeByUserName, mocking the dependencies and unit testing it can seem like a lot of overhead. What your test says is basically,
"when someone calls the GetEmployeeByUserName method on the EmployeeService,
the service should call the correct method on its repository"
Is this an important thing to assert? That's up to you to decide. As the complexity of your service methods increases, however, being able to isolate the dependencies and test their interactions will become more and more valuable.
You need to seed the FindEmployeeByUsername() Method of your mock:
mockCMS.Setup(repos => repos.FindEmployeeByUsername(It.IsAny<string>())).Returns(newEmp);
otherwise it wont return the expected object, while called within the EmployeeService.
Instead of using multiple repositories which I think was confusing. I simplified it and it works now! Except I'm still not sure how this helps me code better. What did I accomplish with this? (I'm new to Testing/Moq/Integration Tests...etc..) I would really like an answer...to this..
public void GetEmployeeUsername_Using_EmployeeClass()
{
var mockCMS = new Mock<ICMS_Repository>(MockBehavior.Strict);
Employee newEmp = new Employee();
newEmp.User_Name = "testName";
mockCMS.Setup(repos => repos.FindEmployeeByUsername(It.IsAny<Employee>())).Returns(newEmp);
var service = new EmployeeService(mockCMS.Object);
var createResult = service.GetEmployeeByUserName(newEmp);
Assert.AreEqual(newEmp, createResult);
}

Proper way to verify parameters being passed to a Mock are set as expected

Is it acceptable to do asserts in your callbacks if you later verify that the methods were called? Is this the preferred way of making sure my mock is getting the expected parameters passed to it, or should I set a local variable in my callback and do the asserts on that instance?
I have a situation where I have some logic in a Presenter class that derives values based on inputs and passes them to a Creator class. To test the logic in the Presenter class I want to verify that the proper derived values are observed when the Creator is called. I came up with the example below that works, but I'm not sure if I like this approach:
[TestFixture]
public class WidgetCreatorPresenterTester
{
[Test]
public void Properly_Generates_DerivedName()
{
var widgetCreator = new Mock<IWidgetCreator>();
widgetCreator.Setup(a => a.Create(It.IsAny<Widget>()))
.Callback((Widget widget) =>
Assert.AreEqual("Derived.Name", widget.DerivedName));
var presenter = new WidgetCreatorPresenter(widgetCreator.Object);
presenter.Save("Name");
widgetCreator.Verify(a => a.Create(It.IsAny<Widget>()), Times.Once());
}
}
I'm concerned because without the Verify call at the end, there is no guarantee that the assert in the callback would be invoked. Another approach would be to set a local variable in the callback:
[Test]
public void Properly_Generates_DerivedName()
{
var widgetCreator = new Mock<IWidgetCreator>();
Widget localWidget = null;
widgetCreator.Setup(a => a.Create(It.IsAny<Widget>()))
.Callback((Widget widget) => localWidget = widget);
var presenter = new WidgetCreatorPresenter(widgetCreator.Object);
presenter.Save("Name");
widgetCreator.Verify(a => a.Create(It.IsAny<Widget>()), Times.Once());
Assert.IsNotNull(localWidget);
Assert.AreEqual("Derived.Name", localWidget.DerivedName);
}
I feel that this approach is less error prone since it is more explicit, and it's easier to see that the Assert statements will be called. Is one approach preferable to the other? Is there a simpler way to test the input parameter passed to a mock that I'm missing?
In case it is helpful, here is the rest of the code for this example:
public class Widget
{
public string Name { get; set; }
public string DerivedName { get; set; }
}
public class WidgetCreatorPresenter
{
private readonly IWidgetCreator _creator;
public WidgetCreatorPresenter(IWidgetCreator creator)
{
_creator = creator;
}
public void Save(string name)
{
_creator.Create(
new Widget { Name = name, DerivedName = GetDerivedName(name) });
}
//This is the method I want to test
private static string GetDerivedName(string name)
{
return string.Format("Derived.{0}", name);
}
}
public interface IWidgetCreator
{
void Create(Widget widget);
}
EDIT
I updated the code to make the second approach I outlined in the question easier to use. I pulled creation of the expression used in Setup/Verify into a separate variable so I only have to define it once. I feel like this method is what I'm most comfortable with, it's easy to setup and fails with good error messages.
[Test]
public void Properly_Generates_DerivedName()
{
var widgetCreator = new Mock<IWidgetCreator>();
Widget localWidget = null;
Expression<Action<IWidgetCreator>> expressionCreate =
(w => w.Create(It.IsAny<Widget>()));
widgetCreator.Setup(expressionCreate)
.Callback((Widget widget) => localWidget = widget);
var presenter = new WidgetCreatorPresenter(widgetCreator.Object);
presenter.Save("Name");
widgetCreator.Verify(expressionCreate, Times.Once());
Assert.IsNotNull(localWidget);
Assert.AreEqual("Derived.Name", localWidget.DerivedName);
}
What I do is do the Verify with matches in keeping with AAA. And becuase of this the Setup is not required. You can inline it but I separated it out to make it look cleaner.
[Test]
public void Properly_Generates_DerivedName()
{
var widgetCreator = new Mock<IWidgetCreator>();
var presenter = new WidgetCreatorPresenter(widgetCreator.Object);
presenter.Save("Name");
widgetCreator.Verify(a => a.Create(MatchesWidget("Derived.Name"));
}
private Widget MatchesWidget(string derivedName)
{
return It.Is<Widget>(m => m.DerivedName == derivedName);
}
Because of the way your code is structured, you're kind of forced to test two things in one unit test. You're testing that A) your presenter is calling the injected WidgetCreator's create method and B) that the correct name is set on the new Widget. If possible, it'd be better if you can somehow make these two things two separate tests, but in this case I don't really see a way to do that.
Given all that, I think the second approach is cleaner. It's more explicit as to what you're expecting, and if it fails, it'd make perfect sense why and where it's failing.
Just to elaborate on #rsbarro's comment - the Moq failure error message:
Expected invocation on the mock at least once, but was never performed
... is less than helpful for complex types, when determining exactly which condition actually failed, when hunting down a bug (whether in the code or unit test).
I often encounter this when using Moq Verify to verify a large number of conditions in the Verify, where the method must have been called with specific parameter values which are not primitives like int or string.
(This is not typically a problem for primitive types, since Moq lists the actual "performed invocations" on the method as part of the exception).
As a result, in this instance, I would need to capture the parameters passed in (which to me seems to duplicate the work of Moq), or just move the Assertion inline with Setup / Callbacks.
e.g. the Verification:
widgetCreator.Verify(wc => wc.Create(
It.Is<Widget>(w => w.DerivedName == "Derived.Name"
&& w.SomeOtherCondition == true),
It.Is<AnotherParam>(ap => ap.AnotherCondition == true),
Times.Exactly(1));
Would be recoded as
widgetCreator.Setup(wc => wc.Create(It.IsAny<Widget>(),
It.IsAny<AnotherParam>())
.Callback<Widget, AnotherParam>(
(w, ap) =>
{
Assert.AreEqual("Derived.Name", w.DerivedName);
Assert.IsTrue(w.SomeOtherCondition);
Assert.IsTrue(ap.AnotherCondition, "Oops");
});
// *** Act => invoking the method on the CUT goes here
// Assert + Verify - cater for rsbarro's concern that the Callback might not have happened at all
widgetCreator.Verify(wc => wc.Create(It.IsAny<Widget>(), It.Is<AnotherParam>()),
Times.Exactly(1));
At first glance, this violates AAA, since we are putting the Assert inline with the Arrange (although the callback is only invoked during the Act), but at least we can get to the bottom of the issue.
Also see Hady's idea of moving the 'tracking' callback lambda into its own named function, or better still, in C#7, this can be moved to a Local Function at the bottom of the unit test method, so the AAA layout can be retained.
Building on top of StuartLC's answer in this thread, you follow what he is suggesting without violating AAA by writing an "inline" function that is passed to the Verify method of a mock object.
So for example:
// Arrange
widgetCreator
.Setup(wc => wc.Create(It.IsAny<Widget>(), It.IsAny<AnotherParam>());
// Act
// Invoke action under test here...
// Assert
Func<Widget, bool> AssertWidget = request =>
{
Assert.AreEqual("Derived.Name", w.DerivedName);
Assert.IsTrue(w.SomeOtherCondition);
Assert.IsTrue(ap.AnotherCondition, "Oops");
return true;
};
widgetCreator
.Verify(wc => wc.Create(It.Is<Widget>(w => AssertWidget(w)), It.Is<AnotherParam>()), Times.Exactly(1));

Using Rhino Mocks how can I set a property of a parameter for a Mocked method

Using the new Rhino Mocks 3.5 Arrange/Act/Assert (AAA) Testing style, I'm having problems writing a test.
I have a method that calls a method on a repository class. ActivateFoo, where my Foo object has an IsActive property. The result of the ActivateFoo object should change the property.
Here is sample code:
[TestMethod]
public void Should_update_foo_to_active_inside_of_repository()
{
// arrange
var repo = MockRepository.GenerateMock<IRepository>();
var foo = new Foo() { ID = 1, IsActive = false };
var target = new Presenter(repo);
repo.Expect(x => x.ActivateFoo(foo)).Return(true);
// act
target.Activate(foo);
// assert
Assert.IsTrue(foo.IsActive);
repo.VerifyAllExpectations();
}
I'm guessing that the key piece of code would be inbetween "ActivateFoo(foo))." and "Return(true);".
One point to clarify how the method chaining stuff works behind the scenes, If there is code written on the line I expect, does it matter if it is after Return() or before? (unless of course the solution is using the MethodOptions overload of Expect, or something else).
Thanks in advance for any help.
Thanks to AB Kolan this is the resulting code I used and works.
[TestMethod]
public void Should_update_foo_to_active_inside_of_repository()
{
// arrange
var repo = MockRepository.GenerateMock<IRepository>();
var foo = new Foo() { ID = 1, IsActive = false };
var target = new Presenter(repo);
repo.Expect(x => x.ActivateFoo(foo)).
Do(new Func<Foo, bool>(
delegate(Foo f) { f.IsActive = true; return true; }
));
// act
target.Activate(foo);
// assert
Assert.IsTrue(foo.IsActive);
repo.VerifyAllExpectations();
}
I tend to not like to have to have extra methods of functions for single use of a test, preferring an inline delegate if possible.
To address the issue of is this something I should be doing or not as far as the design. As the names are there, this isn't the exact code and inside of the target.Activate() method. The code in Activate() does some checking and if needed, will do the repository ActivateFoo(), and then check the result of that operation and do other things.
So, it might be possible that at a later time I will have to refactor this out and separate the steps, but for now, I've got it to work.
Thanks
You might want to try something out like this using the Do handler. I honestly feel ActivateFoo should be void return type. But here's the code for ActivateFoo with bool return type.
[TestMethod]
public void Should_update_foo_to_active_inside_of_repository()
{
// arrange
var repo = MockRepository.GenerateMock<IRepository>();
var foo = new Foo() { ID = 1, IsActive = false };
var target = new Presenter(repo);
repo.Expect(x => x.ActivateFoo(foo)).
Do(new ActivateFooDelegate(ActivateFooDelegateInstance));
// act
target.Activate(foo);
// assert
Assert.IsTrue(foo.IsActive);
repo.VerifyAllExpectations();
}
private delegate bool ActivateFooDelegate(Foo f);
public bool ActivateFooDelegateInstance(Foo f)
{
f.IsActive = true;
return f.IsActive;
}
I was not really using this version of RhinoMocks yet, but in the old versions you would have to use a .Do(appropriate delegate) to set the flag and return the value (instead of .Return).
Please let me know if it works, if not I can play around with it.
From the looks of it, ActivateFoo should be a void method. And since you are mocking it out, you shouldn't be verifying that it changes anything on your object.
You would verify that the IsActive property is changed when you were testing your repository method ActivateFoo, not when you are testing the Activate method on the presenter.

The new syntax for Rhino Mocks

I am struggling a bit to understand how the new AAA syntax works in Rhino Mocks. Most of my tests look like this:
[Test]
public void Test()
{
//Setup
ISth sth= mocks.DynamicMock<ISth>();
//Expectations
Expect.Call(sth.A()).Return("sth");
mocks.ReplayAll();
//Execution
FunctionBeingTested(sth);
//...asserts, etc
//Verification
mocks.VerifyAll();
}
How would it look like using AAA syntax?
Most probably like this:
[Test]
public void Test()
{
// Arrange
ISth sth= MockRepository.GenerateMock<ISth>();
sth
.Stub(x => x.A())
.Return("sth");
// Act
FunctionBeingTested(sth);
// Assert
}
To really benefit from the new AAA syntax, you have to change your mind a bit. I try to explain.
There is a major difference in my proposal: there is no "Expect-Verify". So I propose to not expect the call, because there is a return value. I assume that the method can't pass the test when it didn't call sth.A, because it will miss the correct return value. It will fail at least one of the other asserts.
This is actually a good thing.
you can move the Stub to TestInitialize, it does not hurt when the stubbed method is not called in a test (it's not an expectation). Your tests will become shorter.
Your test does not know "how" the system under test does the job, you only check the results. Your tests will become more maintainable.
There is another scenario, where you actually need to check if a method had been called on the mock. Mainly if it returns void. For instance: an event should have been fired, the transaction committed and so on. Use AssertWasCalled for this:
[Test]
public void Test()
{
// Arrange
ISth sth= MockRepository.GenerateMock<ISth>();
// Act
FunctionBeingTested(sth);
// Assert
sth
.AssertWasCalled(x => x.A());
}
Note: there is not return value, so there is no Stub. This is an ideal case. Of course, you could have both, Stub and AssertWasCalled.
There is also Expect and VerifyAllExpectations, which actually behaves like the old syntax. I would only use them when you need Stub and AssertWasCalled in the same test, and you have complext argument constraints which you don't want to write twice. Normally, avoid Expect and VerifyAllExpectations
example from Ayende`s blog:
[Test]
public void WhenUserForgetPasswordWillSendNotification_UsingExpect()
{
var userRepository = MockRepository.GenerateStub<IUserRepository>();
var notificationSender = MockRepository.GenerateMock<INotificationSender>();
userRepository.Stub(x => x.GetUserById(5)).Return(new User { Id = 5, Name = "ayende" });
notificationSender.Expect(x => x.Send(null)).Constraints(Text.StartsWith("Changed"));
new LoginController(userRepository, notificationSender).ForgotMyPassword(5);
notificationSender.VerifyAllExpectations();
}
Changes in yours test
[Test]
public void Test()
{
//Arrange
var sth= MockRepository.GenerateMock<ISth>();
sth.Expect(x=>sth.A()).Return("sth");
//Act
FunctionBeingTested(sth);
//Assert
sth.VerifyAllExpectations();
}
But that's just a long shot. Wrote it as i suspect it to be.

how to interpret this (rhino) mock unit test failure msg

I am trying to test that a method to load a UI matrix is being loaded properly. The test fails unless I tell the mock framework to ignore the argument passed, giving me the following message:
Rhino.Mocks.Exceptions.ExpectationViolationException :
ITimeSheetMatrixWidget.Load
(Smack.ConstructionAdmin.Domain.TransferObjects.TimeSheetDtoAssembler
+d__1); Expected #1, Actual #0.
What is interesting is that the message is somehow picking up a call made to another object that assembles DTOs from the domain model - I don't get it!
Here is the interface / method Sut is:
public interface ITimeSheetMatrixWidget : IMatrixWidget {
.....
void Load(IEnumerable<DynamicDisplayDto>activities);
.....
}
And here is the test:
[Test]
public void SettingTheWidget_TriggersLoad_NonProjectActivities() {
var f = _getFacade();
// create test activities
TestDataFactory.SetupTestActivities(f);
Assert.That(f.NonProjectDtos.Count(), Is.GreaterThan(0));
// create the presenter
var filterService = MockRepository.GenerateStub<IProjectFilterService>();
var view = MockRepository.GenerateStub<ITimeSheetView>();
var timeSheetPresenter = new TimeSheetPresenter(f, filterService, view);
// inject the mocked widget & trigger the Load
var widget = MockRepository.GenerateMock<ITimeSheetMatrixWidget>();
timeSheetPresenter.ActivityMatrix = widget;
widget.AssertWasCalled(x => x.Load(f.NonProjectDtos),
mo =>mo.IgnoreArguments()); <-- ok, but not useful
//widget.AssertWasCalled(x => x.Load(f.NonProjectDtos)); <-- generates the Exception
}
Can someone explain the failure message?
As an aside, I did post this on the Rhino Mocks forum this morning but traffic there looks like it is very low.
Thank you for your help!
Berryl
Rhino was stating the fact that the way the test was laid out, I wasn't getting the call I'd told it to expect. The test below is an effective way to test an IEnumerable argument:
[Test]
public void ProjectMatrix_Injection_IsLoaded()
{
_projectMatrix = MockRepository.GenerateMock<ITimeSheetMatrixWidget>();
var dtos = _facade.ProjectDtos;
_projectMatrix.Expect(x => x.Load(Arg<IEnumerable<DynamicDisplayDto>>.List.Equal(dtos))).Return(dtos.Count());
new MatrixEntryService(_facade, _projectMatrix, _nonProjectMatrix, _totalMatrix);
_projectMatrix.VerifyAllExpectations();
}
The first trick is using the Rhino argument constraints:
Arg<IEnumerable<DynamicDisplayDto>>
The second trick is to use the List extension, instead of Is:
List.Equal(dtos)
I think it expected one call but got none.

Categories