Search code examples
powershellpester

Pester Test for scriptproperty return type


I am new to pester and trying to create tests for PowerShell class modules. I am trying to determine how to test for my particular method of implementing properties for my classes.

The basic structure that I use is:

class TestClass {
    hidden [string] $_TestProp = $($this | Add-Member -MemberType ScriptProperty -Name TestProp -Value {
            return $this._TestProp
        } -SecondValue {
            param([string]$Value)
            $this._TestProp = $Value
        }
    )
}

This structure, while more work, does allow me the ability to use what I deem "normal" getter\setter functionality within my classes. What I am trying to test is making sure that this property is of type string. I've attempted to try and view the AST for the Getter script block but I wasn't able to find the return type of the scriptblock.

Does anyone have any ideas as to how I would test for the return type of a scriptblock?

Update

As per a suggestion in the comments, I have rewritten the class as such

class TestClass {
    hidden [string] $_TestProp 

    TestClass(){
        $this | Add-Member -MemberType ScriptProperty -Name TestProp -Value {
            return $this._TestProp
        } -SecondValue {
            param([string]$Value)
            $this._TestProp = $Value
        }
    }
}

Functionally it is still the same the add member section was just moved to the constructor area instead of the declaration.


Solution

  • After doing some additional research I was able to come up with the following method of getting the information I was looking for

    $Instance = [TestClass]::new()
    $PropName = "TestProp"
    $PublicProp = $Instance.PSObject.Properties | Where-Object {$_.Name -eq "$($PropName)"}
    $BackingProp = $Instance.PSObject.Properties["_$($PropName)"]
    $BackingProp.TypeNameOfValue -eq $PublicProp.SetterScript.Ast.ParamBlock.Parameters.StaticType.FullName
    

    This ensures that the Setter value being passed in is the same type as the backing property