How to test endpoint that returns 400 Bad Request correctly

I have written a number of endpoint tests successfully with Pester, but now I need to verify that an endpoint returns Status Code 400 (Bad Request) correctly for various kinds of malformed file input. How can I do this? I have tried like this:

 	It 'Create User Spec, fail on no origin' {
		$File = 'UserVehicleNoOrigin.json'
		$Response = Invoke-WebRequest -Method 'POST' -URI http://localhost:5000/xxxxx -ContentType 'application/json' -InFile $File
		$Response.StatusCode | Should -BeExactly '400'
		$Response.Content | Should -BeExactly '1'
	}

But Pester seems to treat any test returning 400 as a failure. I get this output

  [-] Create User Spec, fail on no origin 311ms
    WebException: The remote server returned an error: (400) Bad Request.
    at <ScriptBlock>, C:\Users\xxxxx\Specifications\Server\Test\UserVehicle.Tests.ps1: line 17

in red, as if it’s a test failure, and the response content is not checked. Thanks for any guidance.

You could test for that error.

{... } | Should -Throw -ExpectedMessage "The remote server returned an error: (400) Bad Request"

Thank you. That helps. It shows the test as passing (in green), but it doesn’t check the $Response.StatusCode and $Response.Content conditions. To show that, I’ve changed the test like this:

	It 'Create User Spec, fail on no origin' {
		{
			$File = 'UserVehicleNoOrigin.json'
			$Response = Invoke-WebRequest -Method 'POST' -URI http://localhost:5000/xxxxx -ContentType 'application/json' -InFile $File
			$Response.StatusCode | Should -BeExactly '200'
			$Response.Content | Should -BeExactly '777777'
		} | Should -Throw -ExpectedMessage "The remote server returned an error: (400) Bad Request."
	}

with $Response.StatusCode and $Response.Content conditions that are not what’s expected. The new output is like this:

  [+] Create User Spec, fail on no origin 399ms

Is there a way to have those conditions still be checked?

I believe that Invoke-WebRequest throws a terminating error so Prasoon’s suggestion should work. Otherwise, you could put a try/catch block in there and handle the error in the catch block but it’d just be simpler to test the exception directly.

Correction – I don’t need the $Response.StatusCode | Should -BeExactly check anymore because checking the thrown message accomplishes that, but I still need the $Response.Content | Should -BeExactly check (unless I can find a different way to test that).

With that error being thrown, nothing gets stored in the variable. Hence the other checks cannot be done in that way. There is no content expected from a Bad request.