I have a simple silverlight unit test which doesn't work as expected:
DataContext context = Mock.Create<DataContext>(Constructor.Mocked);
List<Resource> resources = new List<Resource>();
Resource resource = new Resource
{
ContentType = "string",
Data = Encoding.UTF8.GetBytes("Test")
};
Mock.Arrange(() => context.Resources.Add(resource)).DoInstead(() => resources.Add(resource));
Mock.Arrange(() => context.Resources.SingleOrDefault()).Returns(resources.SingleOrDefault());
context.Resources.Add(resource);
var loaded = context.Resources.SingleOrDefault();
The resource property is added correctly to the local resources (context.Resources.Add(resource)) list, however when I'm trying to read it back (context.Resources.SingleOrDefault()) nothing gets returned.
In order to return the updated value of resources.SingleOrDefault()
, you will need to use lambda expression in the arrangement, like this:
Mock.Arrange(() => context.Resources.SingleOrDefault())
.Returns(() => resources.SingleOrDefault());
Otherwise, when the context.Resources.SingleOrDefault()
method is called, the mock will return null, which is the value of the resources.SingleOrDefault()
call at the time of the arrangement.