Setup as so:
public interface IFoo
{
void Fizz();
}
[Test]
public void A()
{
var foo = new Mock<IFoo>(MockBehavior.Loose);
foo.Object.Fizz();
foo.Verify(x => x.Fizz());
// stuff here
foo.Verify(x => x.Fizz(), Times.Never()); // currently this fails
}
Basically I'd like to enter some code at the // stuff here to make the foo.Verify(x => x.Fizz(), Times.Never()) pass.
And because this probably constitutes moq/unit testing abuse, my justification is so I can do something like this:
[Test]
public void Justification()
{
var foo = new Mock<IFoo>(MockBehavior.Loose);
foo.Setup(x => x.Fizz());
var objectUnderTest = new ObjectUnderTest(foo.Object);
objectUnderTest.DoStuffToPushIntoState1(); // this is various lines of code and setup
foo.Verify(x => x.Fizz());
// reset the verification here
objectUnderTest.DoStuffToPushIntoState2(); // more lines of code
foo.Verify(x => x.Fizz(), Times.Never());
}
Basically, I have a state object where a fair bit of work (both in terms of making various mock objects and other faffing around) is requires to push it into State1. Then I want to test the transition from State1 to State2. Instead of duplicating or abstracting the code I'd prefer to just re-use the State1 test, push it into State2 and perform my Asserts - all of which I can do except the verification calls.
This is now supported in Moq
Use .Invocations.Clear() on the latest version of the library:
var foo = new Mock<foo>();
foo.Invocations.Clear();
Old answer
I think long after this post was created they added the functionality that the OP had asked for, there is a Moq extension method called Moq.MockExtensions.ResetCalls().
With this method you can do exactly what you wished as shown below:
[Test]
public void Justification()
{
var foo = new Mock<IFoo>(MockBehavior.Loose);
foo.Setup(x => x.Fizz());
var objectUnderTest = new ObjectUnderTest(foo.Object);
objectUnderTest.DoStuffToPushIntoState1(); // this is various lines of code and setup
foo.Verify(x => x.Fizz());
foo.ResetCalls(); // *** Reset the verification here with this glorious method ***
objectUnderTest.DoStuffToPushIntoState2(); // more lines of code
foo.Verify(x => x.Fizz(), Times.Never());
}
Addition to answer by #stackunderflow (haha, nice nick :))
In later versions of Moq, Moq.MockExtensions.ResetCalls() was marked as obsolete. mock.Invocations.Clear() should be used instead:
foo.Invocations.Clear();
I don't think you can reset a mock like this. Instead, if you know that Fizz should be called once when transitioning to state 1, you can do your verifies like this:
objectUnderTest.DoStuffToPushIntoState1();
foo.Verify(x => x.Fizz(), Times.Once()); // or however many times you expect it to be called
objectUnderTest.DoStuffToPushIntoState2();
foo.Verify(x => x.Fizz(), Times.Once());
Having said that, I would still create two separate tests for this. As two tests, it's easier to see whether the transition into state 1 is failing, or the transition into state 2 is failing. Additionally, when tested together like this, if your transition into state 1 fails, the test method exits and your transition into state 2 doesn't get tested.
Edit
As an example of this, I tested the following code with xUnit:
[Fact]
public void Test()
{
var foo = new Mock<IFoo>(MockBehavior.Loose);
foo.Object.Fizz();
foo.Verify(x => x.Fizz(), Times.Once(), "Failed After State 1");
// stuff here
foo.Object.Fizz();
foo.Verify(x => x.Fizz(), Times.Once(), "Failed after State 2");
}
This test fails with the message, "Failed after State 2". This simulates what would happen if your method that pushes foo into State 2 calls Fizz. If it does, the second Verify will fail.
Looking at your code again, since you are calling one method to verify it does/does not call another method on the mock, I think you need to set CallBase to true so that the base DoStuffToPushIntoState2 is called rather than the mock's override.
I have also witnessed the Times.Exactly(1) verification failure across unit tests using MoQ, with a "was called 2 times" error message. I see this as a bug in MoQ, as I would expect clean mock states on every test run.
My work around was to assign a new mock instance and test target in the test setup.
private Mock<IEntityMapper> entityMapperMock;
private OverdraftReportMapper target;
[SetUp]
public void TestSetUp()
{
entityMapperMock = new Mock<IEntityMapper>();
target = new OverdraftReportMapper(entityMapperMock.Object);
}
Depends on which version of Mock you use, I know for sure we can do this
someMockObject.ResetCalls();
This is indeed unit test abuse as you are verifying two things in one test. Your life would be much easier if you took the ObjectUnderTest initialisation out of the test and into a common setup method. Then your tests become much more readable and independant of each other.
More than production code, test code should be optimized for readability and isolation. A test for one aspect of system's behavior should not affect other aspects. It really is much much easier to refactor common code into a setup method than to try to reset the mock objects.
ObjectUnderTest _objectUnderTest;
[Setup] //Gets run before each test
public void Setup() {
var foo = new Mock<IFoo>(); //moq by default creates loose mocks
_objectUnderTest = new ObjectUnderTest(foo.Object);
}
[Test]
public void DoStuffToPushIntoState1ShouldCallFizz() {
_objectUnderTest.DoStuffToPushIntoState1(); // this is various lines of code and setup
foo.Verify(x => x.Fizz());
}
[Test]
public void DoStuffToPushIntoState2ShouldntCallFizz() {
{
objectUnderTest.DoStuffToPushIntoState2(); // more lines of code
foo.Verify(x => x.Fizz(), Times.Never());
}
You could use the Callback method instead of Verify, and count the calls.
This is demonstrated on the Moq Quick Start page, thus:
// returning different values on each invocation
var mock = new Mock<IFoo>();
var calls = 0;
mock.Setup(foo => foo.GetCountThing())
.Returns(() => calls)
.Callback(() => calls++);
// returns 0 on first invocation, 1 on the next, and so on
Console.WriteLine(mock.Object.GetCountThing());
Next approach works fine for me (using Moq.Sequence)
public void Justification()
{
var foo = new Mock<IFoo>(MockBehavior.Loose);
foo.Setup(x => x.Fizz());
var objectUnderTest = new ObjectUnderTest(foo.Object);
objectUnderTest.DoStuffToPushIntoState1(); // this is various lines of code and setup
foo.Verify(x => x.Fizz());
// Some cool stuff
using (Sequence.Create())
{
foo.Setup(x => x.Fizz()).InSequence(Times.Never())
objectUnderTest.DoStuffToPushIntoState2(); // more lines of code
}
}
Let me know if it worked out for you
Related
I am having a test method that asserts if the CreateClient method of the client account repository has been called. Please See the test bellow.
[TestMethod]
public void CreateNewBasicClientAccount_NewBasicClient_CreatesNewClientBasicClient()
{
// Arrange
var clientAccountToCreate = new ClientAccount
{
Name = "Name",
};
var clientAccountToCreateDto = AutoMapper.Mapper.Map<ClientAccount, ClientAccountDto>(clientAccountToCreate);
var clientAccountRepository = A.Fake<IClientAccountRepository>();
var clientAccountManager = new ClientAccountManager(clientAccountRepository);
// Act
clientAccountManager.CreateClient(clientAccountToCreate);
// Assert
A.CallTo(
() => clientAccountRepository.CreateClient(A<ClientAccountDto>.That.IsNotNull<ClientAccountDto>()))
.MustHaveHappened();
A.CallTo(
() => clientAccountRepository.CreateClient(A<ClientAccountDto>.Ignored))
.MustHaveHappened();
A.CallTo(
() => clientAccountRepository.CreateClient(clientAccountToCreateDto))
.MustHaveHappened();
}
The Act portion of my ClientAccountManager class in the test is calling the CreateClient method of the repository
public void CreateClient(ClientAccount client)
{
var clientDto = AutoMapper.Mapper.Map<ClientAccount, ClientAccountDto>(client);
_clientAccountRepository.CreateClient(clientDto);
}
The first two asserts in the test pass, but the more specific 3rd assert fails with result message
InterfaceNameSpace.IClientAccountRepository.CreateClient(clientDto: DtoNameSpace.ClientAccountDto)
Expected to find it at least once but found it #0 times among the calls:
Both the ClientAccount and ClientAccountDto classes have the exact same properties. Input in getting the failed assert to pass would be appreciated as the code is wired up for it to pass but it fails.
This is because the actual ClientAccountDto that is passed to the method is not the same instance as the one you create in your test, so they're not considered equal.
There are several options to solve this:
override the Equals method in ClientAccountDto (not ideal, since you normally wouldn't need this for a DTO)
inject an IMapper into ClientAccountManager, instead of using the static Mapper class, and configure the IMapper to return a specific instance of ClientAccountDto
test specific properties of the ClientAccountDto, like this:
A.CallTo(
() => clientAccountRepository.CreateClient(A<ClientAccountDto>.That.Matches(x => x.Name == "Name")))
.MustHaveHappened();
Unrelated note: you don't need to specify the type again in A<ClientAccountDto>.That.IsNotNull<ClientAccountDto>(), you can just write A<ClientAccountDto>.That.IsNotNull().
I want to assert that a call on my real object (system under test) was called. Here is my test
// Arrange
var contextFactory = A.Fake<IContextFactory>();
var db = A.Fake<IDatabase>();
A.CallTo(() => contextFactory.GetContext()).Returns(db);
var vm = new MainViewModel(contextFactory);
// Act
vm.Loaded();
// Assert
A.CallTo(() => vm.LoadModels(db)).MustHaveHappened();
I'm getting an ArgumentException that says "The specified object is not recognized as a fake object." How do I test that the LoadModels() method in my MainViewModel gets called from the Loaded() method?
EDIT
The reason I'm doing it this way is because the Loaded() method calls a bunch of other methods when the app starts and I don't want to have to setup all the other stuff for each test, I just want to make sure that all the proper methods get called and then test them individually. I'm open to suggestion for a better way of going about this.
Here are the Loaded and LoadModels methods
internal virtual void Loaded()
{
using (var db = _contextFactory.GetContext())
{
LoadModels(db);
// bunch of other method calls
}
}
internal virtual void LoadModels(IDatabase db)
{
Models = new ObservableCollection<Model>(db.Models);
}
It looks like you're verifying a method (vm.LoadModels) that isn't part of the fake (db). You can only verify methods on a fake, not methods that happen to take the fake as an argument.
I ended up moving the functionality of LoadModels() to another class that implements IStartupDataLoader and then I was able to test it like this
// Arrange
var sdl = A.Fake<IStartupDataLoader>();
var exp = A.Fake<ObservableCollection<Model>>();
A.CallTo(() => sdl.LoadModels()).Returns(exp);
var sut = new MainViewModel(sdl);
// Act
sut.Loaded();
// Assert
Assert.That(exp == sut.Models);
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
}
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.