- This topic has 4 replies, 2 voices, and was last updated 2 years, 1 month ago by
June 21, 2018 at 3:44 am #102884
I have a section in my code where if specific criteria isn’t met, it causes a break which ends command execution. This is expected and by design, but now I am writing a Pester test for it and not sure how assert that a break just took place.
In addition, since Write-Host is pretty much against the law, I saw a Microsoft article stating to use [Console]::WriteLine() in place of Write-Host. I am wondering I should change this to something else that writes output for the user to see.
Your thoughts/suggestions are welcomed!
June 21, 2018 at 2:41 pm #102917KeymasterTopics: 18Replies: 4872Points: 1,903Rank: Community Hero
If you’re using the Console class, you might as well just use Write-Host.
But from the scenario you describe, the normal pattern I’d expect would be to throw a terminating exception, using Throw. That will end execution and display whatever error message you specify. This has the advantage of being trappable in the event some other code is calling yours. And, therefore, you can use Pester to ensure an error is or is not thrown base don whatever input you’re feeding it.
June 21, 2018 at 3:15 pm #102934
Look at the end of the article. It does state to consider using Write-Output as an alternative which should work out fine in my current scenario.
I understand what you are saying about using throw. Ill consider your suggestion. Thanks!
June 21, 2018 at 3:19 pm #102935KeymasterTopics: 18Replies: 4872Points: 1,903Rank: Community Hero
Yeah, I helped write the original version of that ;). “Orders of magnitude slower” doesn’t really matter when you’re terminating execution anyway. It’s not like it’s going to take ten minutes; it’s a few milliseconds slower. It’s console output itself you want to avoid; it can’t be captured, redirected, or directly tested.
And Write-Host in v5 and later actually logs to the Informational pipeline.
Using Write-Output as an alternative is flat-out wrong. It’s a terrible pattern as it corrupts the main output pipeline. I’ll speak to someone about that bit.
June 21, 2018 at 3:27 pm #102937
Yeah I read about the Write-host logs to the Informational Pipeline in v5. That is good!
And now that I am implementing the throw statement (which makes better sense to do), I actually have no need to use Write-Host or Write-Output for that matter.
- The topic ‘Mock [Console]::WriteLine & Break’ is closed to new replies.