|
| 1 | +# Writing Pester tests with ModuleBuild |
| 2 | + |
| 3 | +We wont go deep into how to write pester tests, just how they are integrated into ModuleBuild. |
| 4 | + |
| 5 | +ModuleBuild sorts Pester tests in 3 flavours. Meta, Unit and Intergration tests. |
| 6 | + |
| 7 | +- Meta are very basics tests such as file encoding or Tabs vs Spaces |
| 8 | +- Unit testing is a type of testing to check if the small piece of code is doing what it is suppose to do |
| 9 | +- Integration testing is a type of testing to check if different pieces of the modules are working together |
| 10 | + |
| 11 | +You will most likely only write Unit tests for your powershell module. |
| 12 | + |
| 13 | +## Matching the folder structure |
| 14 | + |
| 15 | +When writing tests you are expected to match the folder structure of the src folder. |
| 16 | +For example, if you want to unit test `src\public\Write-SomeTestModule.ps1` you are expected to create the following test file at `tests\unit\public\Write-SomeTestModule.Tests.ps1`. |
| 17 | + |
| 18 | +The `tests\unit\public\Write-SomeTestModule.Tests.ps1` would look something like this. |
| 19 | +The first 8 lines do some 'magic' to replace the path of the current file and match it to the correct source file. |
| 20 | + |
| 21 | +```powershell |
| 22 | +#Requires -Modules Pester |
| 23 | +$here = Split-Path -Parent $MyInvocation.MyCommand.Path |
| 24 | +$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' |
| 25 | +
|
| 26 | +# Since we match the srs/tests stucture we can use this to dotsource the function. |
| 27 | +$here = $here -replace 'tests\\unit', 'src' |
| 28 | +
|
| 29 | +. "$here\$sut" |
| 30 | +
|
| 31 | +Describe "Testing Write-SomeTestModule" -Tags @('UnitTest') { |
| 32 | + it "Should return a specific string: (Yerp. This is a function.)" { |
| 33 | + $result = Write-SomeTestModule |
| 34 | + $result | Should -Be "Yerp. This is a function." |
| 35 | + } |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +## Tagging your tests |
| 40 | + |
| 41 | +To support different kind of tests ModuleBuild uses Tags in the pester files. These are specified in `Describe` as following: |
| 42 | + |
| 43 | +```powershell |
| 44 | +Describe "Testing Write-SomeTestModule" -Tags @('UnitTest') { |
| 45 | + ... |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +During the build process pester is started multiple times and told to run tests with tag X. This ensure only specific type of tests are ran when we want them to. |
| 50 | + |
| 51 | +Possible tags: |
| 52 | + |
| 53 | +- UnitTest |
| 54 | +- MetaTest |
| 55 | +- IntergrationTest |
0 commit comments