문제

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