need to mock SqlCommand Object

147 views
Skip to first unread message

Ankit Gupta

unread,
Jan 7, 2016, 10:05:07 AM1/7/16
to Pester
Function definition:

function New-SqlCommand
{
    return New-Object ("System.Data.SQLClient.SQLCommand")
}

Implementation:
$deleteCmd = New-SqlCommand
$deleteCmd.Connection = $Connection
$deleteCmd.Transaction = $Transaction


How can I mock this New-SqlCommand Object?

I was trying something on these line:
$NewSqlCommand = @"
        public class MockSqlCommand
        {
            public System.Data.SqlClient.SqlConnection Connection { get; set; }
            public System.Data.SqlClient.SqlTransaction Transaction { get; set; }
            public void ExecuteNonQuery() {}
        }
"@
        Add-Type -TypeDefinition $NewSqlCommand -ReferencedAssemblies System.Data -Language CSharp -Debug
        $NewSqlCommand = New-SqlCommand MockSqlCommand 

but this approach didn't worked for me.

Chris Dent

unread,
Feb 17, 2016, 3:56:40 PM2/17/16
to Pester
Is it that you need to expose the methods? If you're not constrained by type you can create:

Mock New-SqlCommand {
  $PSObject = [PSCustomObject]@{
    Connection = $null
    Transaction = $null
  }
  $PSObject | Add-Member ExecuteNonQuery -MemberType ScriptMethod -Value { }
 
  return $PSObject
}

That'll give you an object with Connection and Transaction as Get/Set properties and a method you can execute which returns nothing (void) and does nothing.

Chris
Reply all
Reply to author
Forward
0 new messages