Question

In EPiServer, how would someone go by testing an extension like so:


public static class LinkItemExtensions
    {
        public static T GetTypedPage(this LinkItem link) where T : TypedPageData
        {
            return (T) DataFactory.Instance.GetPage(PageReference.ParseUrl(link.Href));
        }
    }

What I'm trying to do is somehow test the above class with the following code:


[TestFixture]
public class LinkItemExtensionsTests
    {
        [Test]
        public void GetTypedPage_GivenALinkItem_ReturnsTypedPageData()
        {
            var link = new LinkItem();
            var typedPage = link.GetTypedPage();
            Assert.IsAssignableFrom(typeof(StartPageData), typedPage);
        }
    }

The problem occurs when DataFactory.Instance is summoned.

System.TypeInitializationException : The type initializer for 'EPiServer.DataFactory' threw an exception. ----> System.NullReferenceException : Object reference not set to an instance of an object.

So I've tried passing an abstraction of the DataFactory to the extension method like so:


namespace WebTests
{
    [TestFixture]
    public class PageDataExtensionsTests
    {
        [Test]
        public void GetTypedPage_GivenALinkItem_ReturnsTypedPageData()
        {
            var link = new LinkItem();

        var startPage = A.Fake<StartPageData>();

        var pageDataFactory = A.Fake<IDataFactoryFacade>();

        A.CallTo(() => pageDataFactory.GetPage(null))
            .WithAnyArguments()
            .Returns(startPage);

        var typedPage = link.GetTypedPage<StartPageData>(pageDataFactory);

        Assert.IsAssignableFrom(typeof(StartPageData), typedPage);

    }

}

}

And I get

System.InvalidCastException : Unable to cast object of type 'Castle.Proxies.PageDataProxy' to type 'LocalEPiSandbox.Templates.PageTypes.StartPageData'.

How do you approach this?

Was it helpful?

Solution

You should depend on abastractions insted of it's implementations (you should have some facade cladd above DataFactory). Please take a look over More testability to the people with EPiAbstractions!.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top