Search code examples
powershellunit-testingcode-coveragepester

Do my test code and function code need to be in the same directory for Pester Code Coverage to work?


My test and function code were in the same directory and I was getting the results of code coverage which was working fine.

However after splitting the code into seperate directories Src and Tests I am now seeing the error below regarding paths:

Resolve-CoverageInfo : Could not resolve coverage path

How can I ensure that data is written to my code coverage file? The way I am running Pester is through setting config then using the Invoke-Pester command. See below for example:

$files = Get-ChildItem .\Tests -File -Recurse -Include *.*

$config = [PesterConfiguration]::Default
$config.CodeCoverage.Enabled = $true
$config.CodeCoverage.Path = $files
$config.CodeCoverage.OutputFormat = "NUnitXml"
$config.CodeCoverage.OutputPath = "$result_folder/test-coverage.xml"
$config.TestResult.Enabled = $true
$config.TestResult.OutputPath = "$result_folder/test-results.xml"
$config.Filter.Tag = $TAG

Invoke-Pester -Configuration $config 

When I check to see if the test-coverage.xml file is generated it is, however the file is empty.


Solution

  • It is possible to apply code coverage if src and test files are in seperate directories.

    The problem with the above code is that the statement $config = [PesterConfiguration]::Default runs all files with the .tests extension - the $files variable does not specify which files to run. It specifies which files to look at to obtain code coverage results. This problem has arisen due to confusing which files are run and where the src files are located. This line should be modified to include the actual src files (where the Code Coverage tool is analysing the actual functions), for example first line will not work as the code coverage tool is analysing the test files, we must use the second line for correct implementation, which analyses the src files:

    $files = Get-ChildItem .\Tests -File -Recurse -Include *.*

    $files = Get-ChildItem .\Src -File -Recurse -Include *.*