I have a PowerShell script for setting up a website in IIS. It includes the following function:
function Set-IisWebsiteBinding (
[Parameter(Mandatory = $true)]
[string]$SiteName,
[Parameter(Mandatory = $true)]
[Microsoft.Web.Administration.Site]$Website,
[Parameter(Mandatory = $true)]
[array]$WebsiteBindingSettings
)
{
# Set up website bindings ...
}
I'm trying to write tests for the function in Pester. I'd like to create a dummy $Website object to pass to the function under test. The problem is that the Microsoft.Web.Administration.Site type has no constructor. How can I create an object of type Microsoft.Web.Administration.Site in PowerShell if it has no constructor?
I could create one via IISServerManager.Sites.CreateElement() but I'd like to avoid having to depend on using a real IISServerManager. Alternatively, I could get rid of the type coercion for the function parameter $Website, to allow the test code to pass in a hashtable instead of a Microsoft.Web.Administration.Site object. However, I'd prefer to keep the type coercion so it's obvious to future maintainers of the script what the type of the $Website object is.
Is there any way around this lack of a constructor without using a real IISServerManager or removing the type coercion?
[Microsoft.Web.Administration.Site]as a parameter type will force you to at least have the module when testing, otherwise your function would be throwing a type not found exception. In which case, wouldn't it be better to test with a realSiteinstance ?applicationHost.configto a temp path and use this ctor to instantiate a custom ServerManager instance. Make sure to update default paths in the root configMockSiteClassto mimic theMicrosoft.Web.Administration.Siteclass is a common practice in unit testing. This allows you to simulate the behavior of complex objects without needing the actual dependencies. Pester is a powerful testing framework for PowerShell, and it supports mocking, which is essential for isolating the code under test. By using a mock class, you can keep the type coercion in your function parameters, which helps maintain clarity about the expected types and improves code readability for future maintainers.$site = New-MockObject -Type ([Microsoft.Web.Administration.Site])however that will require you to have the module pre-loadedNew-MockObjectis absolutely perfect for my use case. I have no problem loadingMicrosoft.Web.Administration.dllfor testing. If you'd like to make it an answer I'll accept it.