locked
Invalid cast of a Mole to a Moled type RRS feed

  • Question

  • Hello Experts,

    I need some help in the issue:

    I have some SharePoint code to unit test

    public override void FeatureActivated(SPFeatureReceiverProperties properties)
            {
                // <pex>
                if (properties == (SPFeatureReceiverProperties)null)
                    throw new ArgumentNullException("properties");
                // </pex>
                SPWeb web = (SPWeb) properties.Feature.Parent;
                SPList list = web.Lists[0];
                list.OnQuickLaunch = true;
                list.Update();
            }

    I am moling the SPFeatureReceiverProperties like this

    public class SPFeatureReceiverPropertiesFactory : IPexClassFactory<SPFeatureReceiverProperties>
        {
            public SPFeatureReceiverProperties Create()
            {
                BSPFeatureReceiverProperties props = new BSPFeatureReceiverProperties();
                BSPFeature feature = new BSPFeature();
                BSPWeb web = new BSPWeb();
                SPList list = new BSPList();
    
                props.Feature = feature;
                feature.Parent = web;
                web.Lists.SetOne(list);
    
                return props;
            }
        }

    And I get System.InvalidCastException: Unable to cast object of type 'Microsoft.SharePoint.Behaviors.BSPWeb' to type 'Microsoft.SharePoint.SPWeb' in this line of code.

    SPWeb web = (SPWeb) properties.Feature.Parent;

    Parent is of type Object and it returns an actual object of type BSPWeb.

    My question is - how can I unit test this piece of code?

    Update: the version of Pex Moles dlls is 0.94.0.0
    • Edited by Mak.m Friday, May 4, 2012 12:58 PM Added mocking framework version
    Friday, May 4, 2012 12:52 PM

Answers

  • I found the solution myself. The factory method should be implemented like this:

    public class SPFeatureReceiverPropertiesFactory : IPexClassFactory<SPFeatureReceiverProperties>
        {
            public SPFeatureReceiverProperties Create()
            {
                BSPFeatureReceiverProperties props = new BSPFeatureReceiverProperties();
                BSPFeature feature = new BSPFeature();
                BSPWeb web = new BSPWeb();
                BSPList list = new BSPList2();
    
                props.Feature = feature;
                feature.Parent = web.Instance;
                web.Lists.SetOne(list);
    
                return props;
            }
        }
    I was very close in the beginning but it took me some time to finally do a tiny step to complete this challenge.


    • Marked as answer by Mak.m Friday, May 4, 2012 2:06 PM
    Friday, May 4, 2012 2:06 PM