PowerShell quickie – function to make your Mocks faster

In C#, writing unit tests is king, and Moq is the hotness we use to Mock objects and methods, like the MockObjects we get with Pester in PowerShell.

But one rough part of it is the syntax for Moq, which requires you to write a handler and specify each input argument, which can get pretty verbose and tiresome.

To ease this up, try this function, which will take a method signature and convert it into a sample Mock.Setup or Mock.Verify block, ready for testing

Creates your Moq.Setups for you!
Provide a method signature to receive an example of a basic, lazy Mock for the method
$myMethodSignature = "
string someToken,
int someIntValue = 10,
bool someBoolValue = false,
TimeSpan delayLookup = default,
CancellationToken cancellationToken
New-MoqMethodConfiguration $myMethodSignature
Another example of how to use this cmdlet
Function New-MoqMethodConfiguration{
$Verify = $false
$outputs = New-Object System.Collections.ArrayList
$methodName = $methodSignature.Split('(')[0]
Write-Verbose "found method of name $methodName"
$parms= $methodSignature.Split('(')[1..10].Split("`n").Trim().Replace(')','')
Write-Verbose "found $($parms.Count) parameters"
ForEach($parm in $parms){
if($parm.Length -le 0){continue}
Write-Verbose "processing $parm "
$outputs.Add("It.IsAny<$($parm.Split()[0])>()") | Out-Null
$paramMatcher = $outputs -join ","
if ($Verify){
Write-output ".Verify(m=>m.$($methodName)($paramMatcher), Times.Once)"
Write-output ".Setup(m=>m.$($methodName)($paramMatcher)).Returns…"

Have a code issue? Share your code by going to Gist.github.com and pasting your code there, then post the link here!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.