Mocking SPAttachmentCollection in SharePoint

3 posts, 0 answers
  1. Andy
    Andy avatar
    2 posts
    Member since:
    Jun 2009

    Posted 21 Jan 2011 Link to this post

    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. Andy
    Andy avatar
    2 posts
    Member since:
    Jun 2009

    Posted 21 Jan 2011 Link to this post

    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();
    }
  3. DevCraft R3 2016 release webinar banner
  4. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 24 Jan 2011 Link to this post

    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
Back to Top