Вопрос

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.

Другие советы

I don;t think you should do stubbing on the .SingleOrDefault. It is .NET FW System.Lynq extension and it is well tested. Why I meant well tested means that there is no real point in stubbing this method. You ALWAYS assume it ALWAYS gives the SingleOrDefault instance.

With your Unit Test you can stub the collection List that return by the Resources. Then simply access the SingleOrDefault. The below test passes

    [TestMethod]
    public void YourReadableTestMethod()
    {
        var context = Mock.Create<DataContext>(Constructor.Mocked);
        context.Resources = new List<Resource>();
        var resources = new List<Resource>();

        var resource = new Resource {
            ContentType = "string",
            Data = Encoding.UTF8.GetBytes("Test")
        };
        resources.Add(resource);

        Mock.Arrange(() => context.Resources).ReturnsCollection(resources);


        context.Resources.Add(resource);

        var loaded = context.Resources.SingleOrDefault();
        Assert.IsNotNull(loaded);
    }   
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top