I have gone through all the previous answers and none of them solve my problem.
lets say that i have the following code:
public interface ISomeInterface
{
int SomeMethod(int a, string b);
}
Now i have a common mocking class that defines some default behaviour for the above method
public class CommonMock
{
public Mock<ISomeInterface> MockInterface = new Mock<ISomeInterface>().Setup(x => x.SomeMethod(It.IsAny<int>(), It.IsAny<string>())).Returns(It.IsAny<int>());
}
I need some default behaviour because I have a whole lot of test cases which need a default behaviour.
But in some specific test scenarios, in a totally separate test class, i need to be able to return a different value as i am testing some specific test case.
Something like below:
[Test]
public void TestSomeMethodSpecific()
{
var commonMock = new CommonMock();
commonMock.MockInterface.Setup(x => x.SomeMethod(It.IsAny<int>(), It.IsAny<string>())).Returns(42);
// Do some test based on the new return value
}
How can I achieve that?
Below i am attaching a bit of the actual code:
Common Setup
public class MockStore
{
public Mock<IProcessHandler> ProcessHandler = new Mock<IProcessHandler>();
ProcessHandler.Setup(x => x.GetCurrentProcessRunId()).Returns(It.IsAny<int>());
}
Overridden Setup in a test class
var mockstore = new MockStore();
mockStore.ProcessHandler.Setup(x => x.GetCurrentProcessRunId()).Returns(25);
And there are almost 50 to 70 such mocks each of which return from simple types to complex classes.
That should work? If you create a subsequent setup on a method and it's non-conditional (no constraints on the arguments) then it removes all previous setups for the method.
You can see my answer here that explains it with the source code.
If you want multiple Setups that are conditional, to return different values based on the arguments, then see How to setup a method twice for different parameters with mock.
Without seeing your full code, perhaps you are already using conditional Setups. In which case the order is important and perhaps you are overriding an earlier Setup with a more general one.
You could have global mock objects that you modify as you go. For instance I have this:
[TestClass]
public class StoreServiceTest
{
Mock<IAccess> mockAccess;
Mock<IAccess> mockAccessNoData;
Mock<IDataReader> mockReader;
Mock<IDataReader> mockReaderNoData;
Mock<IStoreService> mockStoreService;
And then on the TestInitiailize, I Setup the default implementation as follows:
mockReader = new Mock<IDataReader>();
mockReader.Setup(m => m.IsDBNull(It.IsAny<int>())).Returns(false);
mockReader.Setup(m => m.GetString(It.IsAny<int>())).Returns("stub");
mockReader.Setup(m => m.GetBoolean(It.IsAny<int>())).Returns(true);
mockReader.Setup(m => m.GetInt32(It.IsAny<int>())).Returns(32);
mockReader.SetupSequence(m => m.Read()).Returns(true).Returns(false); // setup sequence to avoid infinite loop
mockAccess = new Mock<IAccess>();
mockAccess.Setup(m => m.ReadData(It.IsAny<string>(), It.IsAny<object[]>())).Returns(mockReader.Object);
mockReaderNoData = new Mock<IDataReader>();
mockReaderNoData.Setup(m => m.Read()).Returns(false);
mockAccessNoData = new Mock<IAccess>();
mockAccessNoData.Setup(m => m.ReadData(It.IsAny<string>(), It.IsAny<object[]>())).Returns(mockReaderNoData.Object);
mockStoreService = new Mock<IStoreService>();
And now for a default kind of test, all I do is pass the mockReader.Object which should have the default implementation since every test begins with TestInitialize, and then for a special case, say I want to return "sub" instead of "stub" for IDataReader's GetString() method, I can do something like this:
mockReader.Setup(m => m.GetString(It.IsAny<int>())).Returns((int col) => {
if (col == 2) return "sub";
else return "stub";
});
Hope that helps!
I have a service layer which calls a repository layer to fetch data, then do work upon the return object. I want to test the expression being sent into the repository "get" method, say in case the primary key becomes a compound key or something.
Example:
public async Task ArchiveAsync(Domain.Person person)
{
Data.Person entityModel = await _repo.SingleOrDefaultAsync<Data.Person>(p => p.Id == person.Id);
// Stuff is done here...
}
So, in this example, the domain object is passed in, the data object is fetched, and something is done to it. I want to test the expression being passed into the SingleOrDefaultAsync method.
Thoughts?
It's probably better to refactor your code and make the "expression" a proper entity.
The Specification pattern is perfect for your case.
Vladimir Khorikov has written a great,simple article about this: Specification pattern: C# implementation
He has a sample project published on GitHub here
In case the link becomes invalid,I add the main core logic here.
Your repository will look like this:
public IReadOnlyList<T> Find(Specification<T> specification)
{
using (context))
{
return context.DbSet<T>()
.Where(specification.ToExpression())
.ToList();
}
}
For the Specification class you can find many implementations.
It a small utility class that is converted to an expression eventually
If you design your app like that you can easily Test your Specification(which practically is your expression)
I'm not sure that it's a good idea to test expressions. But you may try, if you wish. I have at least one idea for such request.
It will be required to provide a mock instead of your repository, you may use any library you wish. Moq or NSubstitute as an example.
Then, you should get Expression<Func<Domain.Person, bool>> object passed to your repository on SingleOrDefaultAsync invocation. That's should be pretty straightforward with most mocking libs.
And for the last, you will need to compile your expression into Func<Domain.Person, bool> and assert that it returns true for Domain.Person object with expected Id and false otherwise.
And a small snapshot to illustrate, I'm assuming here that there is only one argument, there is the only invocation on repository object and that Domain.Person.Id has public setter.
var repository = Substitute.For<IRepository>();
var service = new Service(repository);
var person = new Domain.Person { Id = 42 };
await service.ArchiveAsync(person);
var call = repository.ReceivedCalls().First();
var arg = call.GetArguments().First();
var expr = (Expression<Func<Domain.Person, bool>>)arg;
var func = expr.Compile();
Assert.True(func(person));
Assert.False(func(new Domain.Person {Id = 1}));
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 have a Dictionary that I am using to avoid writing big if statements. It maps an enum to an action. It looks like this:
var decisionMapper = new Dictionary<int, Action>
{
{
(int) ReviewStepType.StandardLetter,
() =>
caseDecisionService.ProcessSendStandardLetter(aCase)
},
{
(int) ReviewStepType.LetterWithComment,
() =>
caseDecisionService.ProcessSendStandardLetter(aCase)
},
{
(int) ReviewStepType.BespokeLetter,
() =>
caseDecisionService.ProcessSendBespokeLetter(aCase)
},
{
(int) ReviewStepType.AssignToCaseManager,
() =>
caseDecisionService.ProcessContinueAsCase(aCase)
},
};
then I call it like this in my method:
decisionMapper[(int) reviewDecisionRequest.ReviewStepType]();
My question is how can I unit test these mappings?
(I am using Nunit and c# 4.0)
How can I assert that when I call my decisionMapper - that 1 is equal to the call -caseDecisionService.ProcessSendStandardLetter(aCase).
Thanks very much.
You can't compare anonymous delegates (see this link). You have to use a little bit of reflection to check the Method property of the Action delegate. It has to match the MethodInfo of the caseDecisionService method that should be invoked. For example (You may rewrite to use a function to make code shorter):
MethodInfo methodToCall =
decisionMapper[(int)ReviewStepType.StandardLetter].Method;
MethodInfo expectedMethod =
typeof(CaseDecisionService).GetType().GetMethod("ProcessSendStandardLetter");
Assert.AreSame(expectedMethod, methodToCall);
I personally wouldn't bother writing a unit test which directly checks which action is invoked in each case.
Assuming this dictionary is part of a larger system, I'd write one test which goes through each of the Dictionary actions via whatever class contains the Dictionary. I want to check my code gives me outcomes I expect (the outcome of calling ProcessSendStandardLetter() or ProcessSendBespokeLetter(), for example); I'm less interested in checking exactly how it does it.
Thanks everyone for helping with this. This was what I did in the end.
I mocked the Action Service call, then invoked the dictionary's value, then called AssertWasCalled / AssertWasNotCalled. Like this:
mapper[(int) ReviewStepType.StandardLetter].Invoke();
caseDecisionService.AssertWasCalled(c => c.ProcessSendStandardLetter(aCase),
options => options.IgnoreArguments());
caseDecisionService.AssertWasNotCalled(c =>
c.ProcessSendBespokeLetter(aCase),
options => options.IgnoreArguments());
caseDecisionService.AssertWasNotCalled(c =>
c.ProcessContinueAsCase(aCase),
options => options.IgnoreArguments());
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.