1

I'm attempting to test a function that has a strongly-typed parameter, using a object of the same type. Unfortunately, this object is created by a factory and doesn't have a constructor. The factory requires server access and authentication to create it. The strongly-typed parameter is requirement for this function's processing.

Is there a way to create a mock object that doesn't require the factory, but will still be interpreted as the desired type (CrystalDecisions.Enterprise.Desktop.FavoritesFolder)?

Invoke-Foo.ps1:

function Invoke-Foo {

    params(
    [CrystalDecisions.Enterprise.Desktop.FavoritesFolder]$folder
    )

    return $folder.Title

}

Invoke-Foo.Tests.ps1:

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"

Add-Type -AssemblyName 'CrystalDecisions.Enterprise.Desktop.FavoritesFolder, Version=14.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

Describe "Invoke-Foo" {

    # arrange
    $expected = 'Foobar'

    # error generated here
    $folder = New-Object CrystalDecisions.Enterprise.Desktop.FavoritesFolder
    $folder.Title = $expected

    # act
    $actual = Invoke-Foo $folder

    It "returns the name of the folder" {

        # assert
        $actual | should Be $expected

    }

}

The test fails:

PS> Invoke-Pester
Describing Invoke-Foo
 [-] Error occurred in Describe block 62ms
   PSArgumentException: A constructor was not found. Cannot find an appropriate constructor for type CrystalDecisions.Enterprise.Desktop.FavoritesFolder.
   at <ScriptBlock>, C:\Users\XXX\Desktop\Foo\Invoke-Foo.Tests.ps1: line 12
Tests completed in 62ms
Passed: 0 Failed: 1 Skipped: 0 Pending: 0 Inconclusive: 0
craig
  • 25,664
  • 27
  • 119
  • 205

0 Answers0