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.
Related
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);
}
I have the following method:
public void MoveChannelUp(string channelName)
{
var liveChannels = _repository.GetChannels<LiveChannel>();
var channels = GetModifiedChannelsList(channelName, liveChannels);
_repository.SaveChannels(channels);
}
I want to set up an expectation on the SaveChannels() call so that the correct channels parameter is passed in.
I tried :
channelsRepository.Setup(x => x.SaveChannels(reorderedChannels));
where reorderedChannels is what I expect the GetModifiedChannelsList() call will return and but I got Mock verification exception (probably due to reorderedChannels is not the same object as channels???)
So it is GetModifiedChanneslsList() which I really want to test (I know I can use reflection to test this)
So how do I test the correct channels list is passed to SaveChannels()?
You can do something like this (I assume there is a type called Channel and the parameter for SaveChannels is List<Channel>; substitute with the actual):
var expectedChannels = new List<Channel> { new Channel() }; // set up expected channels here
var channelsRepo = new Mock<IChannelsRepository>();
// perform your unit test using channelsRepo here, for example:
channelsRepo.Object.SaveChannels(new List<Channel> { new Channel() });
channelsRepo.Verify(x => x.SaveChannels(It.Is<List<Channel>>(l => l.SequenceEqual(expectedChannels)))); // will throw an exception if call to SaveChannels wasn't made, or the List of Channels params did not match the expected.
What this code does is verify that the SaveChannels method is called at least once with the right list of channels. If that does not happen, Verify will throw an exception and your unit test will fail as expected.
I'm writing a unit test for this one method which returns "void". I would like to have one case that the test passes when there is no exception thrown. How do I write that in C#?
Assert.IsTrue(????)
(My guess is this is how I should check, but what goes into "???")
I hope my question is clear enough.
Your unit test will fail anyway if an exception is thrown - you don't need to put in a special assert.
This is one of the few scenarios where you will see unit tests with no assertions at all - the test will implicitly fail if an exception is raised.
However, if you really did want to write an assertion for this - perhaps to be able to catch the exception and report "expected no exception but got this...", you can do this:
[Test]
public void TestNoExceptionIsThrownByMethodUnderTest()
{
var myObject = new MyObject();
try
{
myObject.MethodUnderTest();
}
catch (Exception ex)
{
Assert.Fail("Expected no exception, but got: " + ex.Message);
}
}
(the above is an example for NUnit, but the same holds true for MSTest)
In NUnit, you can use:
Assert.DoesNotThrow(<expression>);
to assert that your code does not throw an exception. Although the test would fail if an exception is thrown even if there was no Assert around it, the value of this approach is that you can then distinguish between unmet expectations and bugs in your tests, and you have the option of adding a custom message that will be displayed in your test output. A well-worded test output can help you locate errors in your code that have caused a test to fail.
I think it's valid to add tests to ensure that your code is not throwing exceptions; for example, imagine you are validating input and need to convert an incoming string to a long. There may be occasions when the string is null, and this is acceptable, so you want to ensure that the string conversion does not throw an exception. There will therefore be code to handle this occasion, and if you haven't written a test for it you will be missing coverage around an important piece of logic.
This helper class scratched my itch with MSTest. Maybe it can scratch yours also.
[TestMethod]
public void ScheduleItsIneligibilityJob_HasValid_CronSchedule()
{
// Arrange
var factory = new StdSchedulerFactory();
IScheduler scheduler = factory.GetScheduler();
// Assert
AssertEx.NoExceptionThrown<FormatException>(() =>
// Act
_service.ScheduleJob(scheduler)
);
}
public sealed class AssertEx
{
public static void NoExceptionThrown<T>(Action a) where T:Exception
{
try
{
a();
}
catch (T)
{
Assert.Fail("Expected no {0} to be thrown", typeof(T).Name);
}
}
}
Don't test that something doesn't happen. It's like assuring that code doesn't break. That's sort of implied, we all strive for non-breaking, bug-less code. You want to write tests for that? Why just one method? Don't you want all your methods being tested that they don't throw some exception? Following that road, you'll end up with one extra, dummy, assert-less test for every method in your code base. It brings no value.
Of course, if your requirement is to verify method does catch exceptions, you do test that (or reversing it a bit; test that it does not throw what it is supposed to catch).
However, the general approach/practices remain intact - you don't write tests for some artificial/vague requirements that are out of scope of tested code (and testing that "it works" or "doesn't throw" is usually an example of such - especially in scenario when method's responsibilities are well known).
To put it simple - focus on what your code has to do and test for that.
I like to see an Assert.Whatever at the end of each test, just for consistency... without one, can I really be sure there's not supposed to be one there?
For me, this is as simple as putting Assert.IsTrue(true);
I know I didn't accidentally put that code in there, and thus I should be confident enough at quick a skim through that this was as intended.
[TestMethod]
public void ProjectRejectsGappedVersioningByDefault() {
var files = new List<ScriptFile>();
files.Add(ScriptProjectTestMocks.GetVersion1to2());
files.Add(ScriptProjectTestMocks.GetVersion3to4());
Assert.Throws<ScriptProject.InvalidProjectFormatException>(() => {
var sut = new ScriptProject(files);
});
}
[TestMethod]
public void ProjectAcceptsGappedVersionsExplicitly() {
var files = new List<ScriptFile>();
files.Add(ScriptProjectTestMocks.GetVersion1to2());
files.Add(ScriptProjectTestMocks.GetVersion3to4());
var sut = new ScriptProject(files, true);
Assert.IsTrue(true); // Assert.Pass() would be nicer... build it in if you like
}
My friend Tim told me about ExpectedException. I really like this b/c it is more succinct, less code, and very explicit that you are testing for an exception.
[TestMethod()]
[ExpectedException(typeof(System.Exception))]
public void DivideTest()
{
int numerator = 4;
int denominator = 0;
int actual = numerator / denominator;
}
You can read way more about it here: ExpectedException Attribute Usage.
With Xunit you can use this:
var exception = Record.Exception(() =>
MethodUnderTest());
Assert.Null(exception);
or for async operations
var exception = await Record.ExceptionAsync(async () =>
await MethodUnderTestAsync());
Assert.Null(exception);
Another way which worked for me is to store it in a variable and check output.
var result = service.Run()
Assert.IsFalse(result.Errors.Any())
using Moq;
using Xunit;
[Fact]
public void UnitTest_DoesNotThrow_Exception()
{
var builder = new Mock<ISomething>().Object;
//Act
var exception = Record.Exception(() => builder.SomeMethod());
//Assert
Assert.Null(exception);
}
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));
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
}