Skip to content

Instantly share code, notes, and snippets.

@paulspencerwilliams
Created March 13, 2014 10:35
Show Gist options
  • Save paulspencerwilliams/9525937 to your computer and use it in GitHub Desktop.
Save paulspencerwilliams/9525937 to your computer and use it in GitHub Desktop.
Moq does not take a snapshot of parameters passed into a mocked method, and any mutation after the 'Act' stage of a test will be picked up if the object reference is used in a callback from a later Verify statement. The below test unexpectedly fails.
using Moq;
using NUnit.Framework;
namespace MockTester
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Test
{
[Test]
public void TheUnitTest()
{
var mockedDao = new MockRepository(MockBehavior.Loose).Create<IDao>();
var sut = new PersonService(mockedDao.Object);
IList<string> names = new[] { "James", "Ken" }.ToList();
sut.CreatePeople(names);
// Note that "Paul" is added AFTER the action (and thus when
// the mock recorded invocation with it....
names.Add("Paul");
mockedDao.Verify(d=>d.SaveItems(It.Is<IList<String>>(l => PaulIsInList (l))), Times.Never);
}
private bool PaulIsInList(IList<string> list)
{
return list.Contains("Paul");
}
}
public class PersonService
{
private readonly IDao _mockedDao;
public PersonService(IDao mockedDao)
{
_mockedDao = mockedDao;
}
public void CreatePeople(IList<String> names)
{
_mockedDao.SaveItems(names);
}
}
public interface IDao
{
void SaveItems(IList<String> names);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment