Search code examples
c#sharepointsharepoint-onlinesharepoint-designersharepoint-2019

Why does Panel from System.Web.UI.WebControls.Panel returns null in unit testing using C#?


I have a designer class with name ExpenseReceipts.aspx.designer.cs in which a partial class ExpenseReciepts contains

public partial class ExpenseReceipts {
    protected global::System.Web.UI.WebControls.Panel ResultPanel;
}

I have another class ExpenseReceipts.aspx.cs within the module which makes use of this ResultPanel.

public partial class ExpenseReceipts : LayoutsPageBase
{
public void HandleRecordsNotFound()
        {
            ResultPanel.Visible = false;
            NoItemsMessage.Text = "No Items Found!!!";
            NoItemsMessage.ForeColor = System.Drawing.Color.Red;
            NoItemsPanel.Visible = true;
        }
}

This works fine as far as the production code goes but the problem arises when I try to write the unit test for the same. I have the following method trying to shim everything here.

        [TestMethod]
        public void HandleRecordsNotFound_ShouldMakeNoResultPanelVisible()
        {
            using (ShimsContext.Create())
            {
                bool flag = false;

                ShimControl.AllInstances.VisibleSetBoolean = (PANEL, BOOLEAN) => { };
                ShimLabel.AllInstances.TextSetString = (LABEL, TEXT) => { };
                ShimWebControl.AllInstances.ForeColorSetColor = (WEBCONTROL, FORECOLOR) => { };
                ShimControl.AllInstances.VisibleSetBoolean = (CONTROL, BOOLEAN) => { flag = true; };
                ExpenseReceipts expenseReceipts = new ExpenseReceipts();
                expenseReceipts.HandleRecordsNotFound();
                Assert.IsTrue(flag);
            }
        }

It FAILS because of the exception thrown in HandleRecordsNotFound saying NUll pointer exception indicating - ResultPanel is null.

Kindly help me fix this. Thanks in advance. PS: I am using Sharepoint 2019.


Solution

  • The Shimming method I was following was wrong. It is not the right way to write tests for the UI controls.

    Here's what I did:

    public void HidePanelControl_ShouldSetVisibleToFalse() {
        Panel panel = new Panel();
        JEUploadWorkflowLinkWPUserControl 
        userControl = new JEUploadWorkflowLinkWPUserControl();
        userControl.HidePanelControl(panel);
        Assert.IsFalse(panel.Visible);
    }