Mocking .NET Objects

This topic contains 2 replies, has 2 voices, and was last updated by  Dave Brannan 10 months, 2 weeks ago.

  • Author
  • #79105

    Dave Brannan


    Does anyone know the requirements for mocking .NET objects? Using New-MockObject works ok for something like System.Diagnostics.Process but not for System.Data.DataRow.

    The mock appears to work but using GetType gives the error "The following exception occurred while retrieving member "GetType": "Object reference not set to an instance of an object."

    Wanted to try and use the reflection method mentioned here

  • #79109

    Adam Bertram

    New-MockObject just creates an object template of sorts but, as you have seen, is not a true object. I use New-MockObject all the time and if I need a method or property like GetType() I'll do this:

    $obj = New-MockObject -Type 'System.Data.DataRow'
    $obj | Add-Member -MemberType ScriptMethod -Name 'GetType' -Force -Value { 'sometthinghere' }
  • #79114

    Dave Brannan

    Doesn't work for me, the Add-Member still fails with "Object reference not set to an instance of an object".

    Was thinking maybe that type lacks a public constructor or the New-MockObject function is not instantiating the class in a way that makes it usable?

You must be logged in to reply to this topic.