This is a migrated thread and some comments may be shown as answers.

Mocking SPAttachmentCollection in SharePoint

2 Answers 74 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Andy
Top achievements
Rank 1
Andy asked on 21 Jan 2011, 06:08 PM
I've got a bunch of tests that need to mock SPAttachmentCollection. In Isolator, I did it like this:


public void CreateAttachmentFromAfterUrl_AttachmentNameNotInAfterUrl_ReturnsNull()
{
    var properties = Isolate.Fake.Instance<SPItemEventProperties>();
 
    Isolate.WhenCalled(() => properties.ListItem.Attachments)
        .WillReturnCollectionValuesOf(new[] { "A","B" });
 
    Isolate.WhenCalled(() => properties.AfterUrl)
        .WillReturn("C");
 
    var attachment = AttachmentFactory.CreateAttachmentFromAfterUrl(properties);
 
    attachment.ShouldBeNull();
}

In JustMock, I've done it like this:

public void CreateAttachmentFromAfterUrl_AttachmentNameNotInAfterUrl_ReturnsNull()
{
    var properties = Mock.Create<SPItemEventProperties>();
    var collection = Mock.Create<SPAttachmentCollection>();
 
    var list = new List<string> {"A", "B"};
 
    Mock.Arrange(() => collection.GetEnumerator()).Returns(list.GetEnumerator());
    Mock.Arrange(() => properties.ListItem.Attachments).Returns(collection);
    Mock.Arrange(() => properties.AfterUrl).Returns("C");
 
    var attachment = AttachmentFactory.CreateAttachmentFromAfterUrl(properties);
 
    attachment.ShouldBeNull();
}

Is there a better way? I would like to use ReturnsCollection() on properties.ListItem.Attachments, but it's unavailable for some reason.

-Andy

2 Answers, 1 is accepted

Sort by
0
Andy
Top achievements
Rank 1
answered on 21 Jan 2011, 10:11 PM
Nevermind...  Everything works exactly as it ought to. I didn't see that ReturnsCollection() is in the Helpers namespace. /facepalm

Works:

public void CreateAttachmentFromAfterUrl_AttachmentNameNotInAfterUrl_ReturnsNull()
{
    var properties = Mock.Create<SPItemEventProperties>();
 
    Mock.Arrange(() => properties.ListItem.Attachments).ReturnsCollection(new[] { "A", "B" });
    Mock.Arrange(() => properties.AfterUrl).Returns("C");
 
    var attachment = AttachmentFactory.CreateAttachmentFromAfterUrl(properties);
 
    attachment.ShouldBeNull();
}
0
Ricky
Telerik team
answered on 24 Jan 2011, 08:19 AM
Hi Andy,

It’s great that things worked for you. Should you have any other issues please don't hesitate to contact us.

Kind Regards,
Ricky
the Telerik team
Browse the videos here>> to help you get started with JustMock
Tags
General Discussions
Asked by
Andy
Top achievements
Rank 1
Answers by
Andy
Top achievements
Rank 1
Ricky
Telerik team
Share this question
or