How to mock external dll functions -New to TDD, powershell and pester, but willing to try

495 views
Skip to first unread message

Odd Erik Solberg

unread,
Mar 14, 2014, 10:57:02 AM3/14/14
to pes...@googlegroups.com
I am trying to figure out how to mock an SFTP component when using Pester. Any suggestions? Should I arrange my code different?

Regards

Code
-----
Add-Type -Path (Join-Path -Path $psScriptRoot "Renci.SshNet.dll")

function Get-FromSFtp 
{
    $fileList=$null
    try
    {
        $sftp=New-Object Renci.SshNet.SftpClient("127.0.0.1","test","test")
        $sftp.Connect()
        if($sftp.IsConnected)
        {               
            $sftp.ChangeDirectory("/test")
   $fileList=$sftp.ListDirectory(".")
        }
return $fileList
    }
    catch [Exception]
    {    
        Write-Host $_.Exception.ToString()
    }
   finally
   {
if(($sftp -ne $null) -and ($sftp.IsConnected))
{
$sftp.Disconnect()
}        
   }
}


Test

Describe  "Get-FromSFtp " {

    Context "start sftp and get filelist back" {
        
        $expected=@("test.txt","test2.txt")
        
        #Not quite sure how to mock this
        #Mock something to give me the Sftp object and the expected return value
        Mock Something something??
        $actual=Get-FromSFtp 

        It "should return a list of files" {
            $actual| Should Be $expected
        }
    
    }
}

Scott Muc

unread,
Mar 14, 2014, 12:15:38 PM3/14/14
to Odd Erik Solberg, pes...@googlegroups.com
This problem is a classic one that's found in regular application code.

The line: 
$sftp=New-Object Renci.SshNet.SFtpClient("127.0.0.1","test","test")

Needs to be wrapped by something like Get-SftpConnection which you can then mock.

Or do you just want to mock Get-FromSFtp?If that's the case, then the test isn't really testing anything except Pester's mocking functionality.

This is where TDD as a design practice shows it's strength. TDD results in easy to test code.

This looks like a good example for a TDD screencast with Pester!


--
You received this message because you are subscribed to the Google Groups "Pester" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pester+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Odd Erik Solberg

unread,
Mar 17, 2014, 10:55:01 AM3/17/14
to pes...@googlegroups.com, Odd Erik Solberg
Thanks for a really quick response.

I might be dobble posting here, but it seems that my previous post disappered.

When I moved the New-Object out to a function I still could not see how to mock the member functions 
Connect
IsConnected
ChangeDirectory
ListDirectory

Would you also move this out to functions?

Regards
Odd Erik Solberg

scot...@gmail.com

unread,
Jun 5, 2014, 9:30:59 PM6/5/14
to pes...@googlegroups.com, odd.erik...@webstep.no
Reply all
Reply to author
Forward
0 new messages