I'm a C# and Moq newb. I have some code that looks like the following and I want to unit test it, using Moq.
Data.Foo.FooDataTable tbl = Adapter.GetFooByID(id);
foreach (Data.Foo.FooRow row in tbl)
{
x = row.bar
...
}
How do I set up the mocks? Current broken attempt:
var adapter = new Mock<FooTableAdapter>();
var table = new Mock<Foo.FooDataTable>();
var rows = new Mock<DataRowCollection>();
var row = new Mock<Foo.FooRow>();
rows.Setup(x => x.GetEnumerator().Current).Returns(row.Object);
table.Setup(x => x.Rows).Returns(rows.Object);
adapter.Setup(x => x.GetFooByID(1)).Returns(table.Object);
_adapter = adapter.Object;
If I don't try to add the row, I get a NullReferenceException in the foreach. If I do try to add the row, I get a System.NotSupportedException: Type to mock must be an interface or an abstract or non-sealed class.
Mocks are awesome and all but they really are testing tools of last resort -- what you reach for when you've got some impossible to create object you can't avoid depending on -- such as HttpContext.
In this case, you probably don't want to create a moq mock of the DataTable -- you can just new up one with appropriate data. What you'd want to moq mock would be the call to Adapter.GetFooById() to spit back your test double of a data table.
Mocks should only be used to create fake dependencies when you want to test the behaviour of something that requires said dependency, but you don't want (or can't) actually create a "real" instance of that dependency. Any test method with more than a couple of mocks is headed in the wrong direction because it's a sign that you have either too many dependencies, or that you are testing too many unrelated things.
In the code you have above, there are no dependencies, so Mocks wouldn't be appropriate really what you need.
You really need to think about what exactly it is you are trying to test here. For the sake of argument let's assume that the code you showed is from a method:
public class MyFooClass
{
public int DoFooFooData(FooAdapter Foo)
{
Data.Foo.FooDataTable tbl = Adapter.GetFooByID(id);
//just imagining what you might do here.
int total=0;
foreach (Data.Foo.FooRow row in tbl)
{
x = row.bar
//just imagining what you might do here.
total+=x;
}
return total;
}
}
Now, let's further suppose that you want to unit test this method. In this case in order to call the method you have to supply a working FooAdapter instance because the method depends on it in order to work
But let's now say that you are not currently in possession of a FooAdapter because it doesn't exist, or maybe you can't supply one because FooAdapter makes a database connection which is a no-no in unit testing.
What we need to do in order to test DoFooFooData is to supply a fake (Mock) FooAdapter, which only implements the GetFooByID method, in order for your function to execute.
To do this you'll have to either make FooAdapter abstract or (I recommend) declare it by interface:
public interface IFooAdapter
{
Data.Foo.FooDataTable GetByID(int id);
}
(later on you'll need to change FooAdapter class to implement IFooAdapter if you want to actually use it with the DoFooFooData method for real)
Now change your method signature:
public void DoFooFooData(IFooAdapter Foo)
{
Data.Foo.FooDataTable tbl = Adapter.GetFooByID(id);
int total=0;
foreach (Data.Foo.FooRow row in tbl)
{
x = row.bar
//just imagining what you might do here
total+=x;
}
return total;
}
And finally in your test method, you can mock this dependency:
void DoFooFooData_DoesSomeFooAndReturns3()
{
var mock = new Mock<IFooAdapter>();
var table = new Data.Foo.FooDataTable();
table.Add(new Data.Foo.FowRow{bar=1});
table.Add(new Data.Foo.FowRow{bar=2});
mock.Setup(m=>m.GetByID(It.IsAny<int>()).Returns(table);
var sut = new MyFooClass();
var expected=3;
var actual=sut.DoFooFooData(mock.Object);
Assert.AreEqual(expected,actual);
}
Of course if you need to Mock FooDataTable as well you can follow the same pattern as you did with the IFooAdapter but you need to stop at this point and ask yourself if you shouldn't be creating a separate test in which you Mock an IFooDataTable and ensure that it does what it's supposed to do (Add method or whatever) and so on...at the point when you were sure that the behavioural contract of IFooDataTable is OK, you'd then implement it as a concrete "stub" which you can then use in place of any FooDataTable references in the context of an IFooAdapter...but now you're into integration tests which is a story for another day...
Update 1, more details
My question was hard to interpret, sorry for that....
Simple question...
How do you test a specific implementation with Moq?
interface IShipping
{
int CalculateCost();
}
class TruckShipping: IShipping
{
int CalculateCost()
{
return 9;
}
}
class Shipping: IShipping
{
int CalculateCost()
{
return 5;
}
}
class CalculateSomethingMore
{
IShipping _shipping;
CalculateSomethingMore(IShipping shipping)
{
// Here I want the TruckShipping implementation!
_shipping = shipping;
}
DoCalc()
{
return _shipping.CalculateCost * 2;
}
}
Without mock it would probably look like (if you don't use DI)
TEST:
var truckShipping = new TruckShipping();
var advancedCalculation = CalculateSomethingMore(truckShipping);
var result = DoCalc();
var expected = 18;
Assert.IsTrue(result == expected);
NUnit, FluentAssertions, MbUnit, xUnit, etc.. doesn't matter :)
Test:
var truckShipping = Mock.Of<IShipping> .... ? I want to test the TruckShipping implementation.
and inject that into CalculateSomethingMore.
If you want to test TruckShipping implementation then you need separate tests for TruckShipping implementation.
Currently you are testing behavior of CalculateSomethingMore, which should return doubled value of cost, calculated by shipping. You don't care which shipping. Responsibility of CalculateSomethingMore is asking shipping about it's cost, and doubling that cost:
Mock<IShipping> shipping = new Mock<IShipping>();
shipping.Setup(s => s.CalculateCost()).Returns(10);
CalculateSomethingMore sut = new CalculateSomethingMore(shipping.Object);
Assert.That(20, Is.EqualTo(sut.DoCalc()));
shipping.VerifyAll();
You can see, that this test uses neither 9 nor 5 as shipping cost. Why? Because you actually don't care what value it will have. Calculating shipping cost is not responsibility of class under test.
Also you need another test for your TruckShipping implementation, which will verify, that TruckShipping calculates shipping cost correctly (this is a responsibility of your shipping object):
TruckShipping sut = new TruckShipping();
Assert.That(9, Is.EqualTo(sut.DoCalc());
Moq is not a testing framework, it's a mockinq framework, so it does not provide testing features.
For testing you can use SharpTestEx, for example you can write:
[TestMethod]
public void VerifyCostIsCorrect()
{
new TruckShipping()
.CalculateCost()
.Should("The TruckShipping implementation returns a wrong cost.").Be.EqualTo(9);
}
You use mocks to replace real dependencies (which often are too complex to instantiate) with faked, lightweight objects. Testing mocked object makes no sense at all because essentially, you'll be testing auto-generated code from some 3rd party library.
Edit:
It's still unclear why would you want to depend on concrete implementation, especially considering you're using IoC and inject IShipping. Anyways, I think you want something that can simulate TruckShipping, but not TruckShipping itself. If so, it's simple:
var shippingMock = new Mock<IShipping>();
// setting up mock to return 9 makes it behave as if it was TruckShipping
shippingMock.Stub(s => s.CalculateCost()).Returns(9);
var advancedCalculation = CalculateSomethingMore(shippingMock.Object);
var result = DoCalc();
var expected = 18;
Assert.IsTrue(result == expected);
I need to test the following method:
CreateOutput(IWriter writer)
{
writer.Write(type);
writer.Write(id);
writer.Write(sender);
// many more Write()s...
}
I've created a Moq'd IWriter and I want to ensure that the Write() methods are called in the right order.
I have the following test code:
var mockWriter = new Mock<IWriter>(MockBehavior.Strict);
var sequence = new MockSequence();
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedType));
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedId));
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedSender));
However, the second call to Write() in CreateOutput() (to write the id value) throws a MockException with the message "IWriter.Write() invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup.".
I'm also finding it hard to find any definitive, up-to-date documentation/examples of Moq sequences.
Am I doing something wrong, or can I not set up a sequence using the same method?
If not, is there an alternative I can use (preferably using Moq/NUnit)?
There is bug when using MockSequence on same mock. It definitely will be fixed in later releases of Moq library (you can also fix it manually by changing Moq.MethodCall.Matches implementation).
If you want to use Moq only, then you can verify method call order via callbacks:
int callOrder = 0;
writerMock.Setup(x => x.Write(expectedType)).Callback(() => Assert.That(callOrder++, Is.EqualTo(0)));
writerMock.Setup(x => x.Write(expectedId)).Callback(() => Assert.That(callOrder++, Is.EqualTo(1)));
writerMock.Setup(x => x.Write(expectedSender)).Callback(() => Assert.That(callOrder++, Is.EqualTo(2)));
I've managed to get the behaviour I want, but it requires downloading a 3rd-party library from http://dpwhelan.com/blog/software-development/moq-sequences/
The sequence can then be tested using the following:
var mockWriter = new Mock<IWriter>(MockBehavior.Strict);
using (Sequence.Create())
{
mockWriter.Setup(x => x.Write(expectedType)).InSequence();
mockWriter.Setup(x => x.Write(expectedId)).InSequence();
mockWriter.Setup(x => x.Write(expectedSender)).InSequence();
}
I've added this as an answer partly to help document this solution, but I'm still interested in whether something similar could be achieved using Moq 4.0 alone.
I'm not sure if Moq is still in development, but fixing the problem with the MockSequence, or including the moq-sequences extension in Moq would be good to see.
I wrote an extension method that will assert based on order of invocation.
public static class MockExtensions
{
public static void ExpectsInOrder<T>(this Mock<T> mock, params Expression<Action<T>>[] expressions) where T : class
{
// All closures have the same instance of sharedCallCount
var sharedCallCount = 0;
for (var i = 0; i < expressions.Length; i++)
{
// Each closure has it's own instance of expectedCallCount
var expectedCallCount = i;
mock.Setup(expressions[i]).Callback(
() =>
{
Assert.AreEqual(expectedCallCount, sharedCallCount);
sharedCallCount++;
});
}
}
}
It works by taking advantage of the way that closures work with respect to scoped variables. Since there is only one declaration for sharedCallCount, all of the closures will have a reference to the same variable. With expectedCallCount, a new instance is instantiated each iteration of the loop (as opposed to simply using i in the closure). This way, each closure has a copy of i scoped only to itself to compare with the sharedCallCount when the expressions are invoked.
Here's a small unit test for the extension. Note that this method is called in your setup section, not your assertion section.
[TestFixture]
public class MockExtensionsTest
{
[TestCase]
{
// Setup
var mock = new Mock<IAmAnInterface>();
mock.ExpectsInOrder(
x => x.MyMethod("1"),
x => x.MyMethod("2"));
// Fake the object being called in order
mock.Object.MyMethod("1");
mock.Object.MyMethod("2");
}
[TestCase]
{
// Setup
var mock = new Mock<IAmAnInterface>();
mock.ExpectsInOrder(
x => x.MyMethod("1"),
x => x.MyMethod("2"));
// Fake the object being called out of order
Assert.Throws<AssertionException>(() => mock.Object.MyMethod("2"));
}
}
public interface IAmAnInterface
{
void MyMethod(string param);
}
The simplest solution would be using a Queue:
var expectedParameters = new Queue<string>(new[]{expectedType,expectedId,expectedSender});
mockWriter.Setup(x => x.Write(expectedType))
.Callback((string s) => Assert.AreEqual(expectedParameters.Dequeue(), s));
Recently, I put together two features for Moq: VerifyInSequence() and VerifyNotInSequence(). They work even with Loose Mocks. However, these are only available in a moq repository fork:
https://github.com/grzesiek-galezowski/moq4
and await more comments and testing before deciding on whether they can be included in official moq releaase. However, nothing prevents you from downloading the source as ZIP, building it into a dll and giving it a try. Using these features, the sequence verification you need could be written as such:
var mockWriter = new Mock<IWriter>() { CallSequence = new LooseSequence() };
//perform the necessary calls
mockWriter.VerifyInSequence(x => x.Write(expectedType));
mockWriter.VerifyInSequence(x => x.Write(expectedId));
mockWriter.VerifyInSequence(x => x.Write(expectedSender));
(note that you can use two other sequences, depending on your needs. Loose sequence will allow any calls between the ones you want to verify. StrictSequence will not allow this and StrictAnytimeSequence is like StrictSequence (no method calls between verified calls), but allows the sequence to be preceeded by any number of arbitrary calls.
If you decide to give this experimental feature a try, please comment with your thoughts on:
https://github.com/Moq/moq4/issues/21
Thanks!
I've just had a similar scenario, and inspired by the accepted answer, I've used the following approach:
//arrange
var someServiceToTest = new SomeService();
var expectedCallOrder = new List<string>
{
"WriteA",
"WriteB",
"WriteC"
};
var actualCallOrder = new List<string>();
var mockWriter = new Mock<IWriter>();
mockWriter.Setup(x => x.Write("A")).Callback(() => { actualCallOrder.Add("WriteA"); });
mockWriter.Setup(x => x.Write("B")).Callback(() => { actualCallOrder.Add("WriteB"); });
mockWriter.Setup(x => x.Write("C")).Callback(() => { actualCallOrder.Add("WriteC"); });
//act
someServiceToTest.CreateOutput(_mockWriter.Object);
//assert
Assert.AreEqual(expectedCallOrder, actualCallOrder);
Moq has a little-known feature called Capture.In, which can capture arguments passed to a method. With it, you can verify call order like this:
var calls = new List<string>();
var mockWriter = new Mock<IWriter>();
mockWriter.Setup(x => x.Write(Capture.In(calls)));
CollectionAssert.AreEqual(calls, expectedCalls);
If you have overloads with different types, you can run the same setup for overloads too.
My scenario was methods without parameters:
public interface IWriter
{
void WriteA ();
void WriteB ();
void WriteC ();
}
So I used Invocations property on the Mock to compare what was called:
var writer = new Mock<IWriter> ();
new SUT (writer.Object).Run ();
Assert.Equal (
writer.Invocations.Select (invocation => invocation.Method.Name),
new[]
{
nameof (IWriter.WriteB),
nameof (IWriter.WriteA),
nameof (IWriter.WriteC),
});
You could also append the invocation.Arguments to check method calls with parameters.
Also the failure message is more clear than just expected 1 but was 5:
expected
["WriteB", "WriteA", "WriteC"]
but was
["WriteA", "WriteB"]
I suspect that expectedId is not what you expect.
However i'd probably just write my own implementation of IWriter to verify in this case ... probably a lot easier (and easier to change later).
Sorry for no Moq advice directly. I love it, but haven't done this in it.
do you maybe need to add .Verify() at the end of each setup? (That really is a guess though i'm afraid).
I am late to this party but I wanted to share a solution that worked for me since it seems as though all of the referenced solutions did not work with verifying the same method call (with the same arguments) multiple times in order. In addition the referenced bug, Moq Issue #478 was closed without a solution.
The solution presented utilizes the MockObject.Invocations list to determine order and sameness.
public static void VerifyInvocations<T>(this Mock<T> mock, params Expression<Action<T>>[] expressions) where T : class
{
Assert.AreEqual(mock.Invocations.Count, expressions.Length,
$"Number of invocations did not match expected expressions! Actual invocations: {Environment.NewLine}" +
$"{string.Join(Environment.NewLine, mock.Invocations.Select(i => i.Method.Name))}");
for (int c = 0; c < mock.Invocations.Count; c++)
{
IInvocation expected = mock.Invocations[c];
MethodCallExpression actual = expressions[c].Body as MethodCallExpression;
// Verify that the same methods were invoked
Assert.AreEqual(expected.Method, actual.Method, $"Did not invoke the expected method at call {c + 1}!");
// Verify that the method was invoked with the correct arguments
CollectionAssert.AreEqual(expected.Arguments.ToList(),
actual.Arguments
.Select(arg =>
{
// Expressions treat the Argument property as an Expression, do this to invoke the getter and get the actual value.
UnaryExpression objectMember = Expression.Convert(arg, typeof(object));
Expression<Func<object>> getterLambda = Expression.Lambda<Func<object>>(objectMember);
Func<object> objectValueGetter = getterLambda.Compile();
return objectValueGetter();
})
.ToList(),
$"Did not invoke step {c + 1} method '{expected.Method.Name}' with the correct arguments! ");
}
}
I am creating a mock for my ITransformer interface.
public interface ITransformer
{
String Transform( String input );
}
I can create a mock that returns an given string based on a specific input:
var mock = new Mock<ITransformer>();
mock.Setup(s => s.Transform("foo")).Returns("bar");
What I would like to do is create a mock with a Transform() method that echoes whatever is passed to it. How would I go about doing this? Is it even possible?
I realise my question might be subverting the way that Moq and mocks in general are supposed to work because I'm not specifying a fixed expectation.
I also know that I could easily create my own class to do this, but I was hoping to find a generic approach that I could use in similar circumstances without having to define a new class each time.
var mock = new Mock<ITransformer>();
m.Setup(i => i.Transform(It.IsAny<string>())).Returns<string>((string s) => { return s;});
var mock = new Mock<ITransformer>();
mock.Setup(t => t.Transform(It.IsAny<string>())).Returns((String s) => s);
This should echo back whatever was supplied to the method.
I can't for the life of me find the proper syntax using the Fluent/AAA syntax in Rhino for validating order of operations.
I know how to do this with the old school record/playback syntax:
MockRepository repository = new MockRepository();
using (repository.Ordered())
{
// set some ordered expectations
}
using (repository.Playback())
{
// test
}
Can anyone tell me what the equivalent to this in AAA syntax for Rhino Mocks would be. Even better if you can point me to some documentation for this.
Try this:
//
// Arrange
//
var mockFoo = MockRepository.GenerateMock<Foo>();
mockFoo.GetRepository().Ordered();
// or mockFoo.GetMockRepository().Ordered() in later versions
var expected = ...;
var classToTest = new ClassToTest( mockFoo );
//
// Act
//
var actual = classToTest.BarMethod();
//
// Assert
//
Assert.AreEqual( expected, actual );
mockFoo.VerifyAllExpectations();
Here's an example with interaction testing which is what you usually want to use ordered expectations for:
// Arrange
var mockFoo = MockRepository.GenerateMock< Foo >();
using( mockFoo.GetRepository().Ordered() )
{
mockFoo.Expect( x => x.SomeMethod() );
mockFoo.Expect( x => x.SomeOtherMethod() );
}
mockFoo.Replay(); //this is a necessary leftover from the old days...
// Act
classToTest.BarMethod
//Assert
mockFoo.VerifyAllExpectations();
This syntax is very much Expect/Verify but as far as I know it's the only way to do it right now, and it does take advantage of some of the nice features introduced with 3.5.
The GenerateMock static helper along with Ordered() did not work as expected for me. This is what did the trick for me (the key seems to be to explicitly create your own MockRepository instance):
[Test]
public void Test_ExpectCallsInOrder()
{
var mockCreator = new MockRepository();
_mockChef = mockCreator.DynamicMock<Chef>();
_mockInventory = mockCreator.DynamicMock<Inventory>();
mockCreator.ReplayAll();
_bakery = new Bakery(_mockChef, _mockInventory);
using (mockCreator.Ordered())
{
_mockInventory.Expect(inv => inv.IsEmpty).Return(false);
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, false));
}
_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);
_mockChef.VerifyAllExpectations();
_mockInventory.VerifyAllExpectations();
}
tvanfosson's solution does not work for me either. I needed to verify that calls are made in particular order for 2 mocks.
According to Ayende's reply in Google Groups Ordered() does not work in AAA syntax.