質問

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