Search code examples
jmeterhttpresponsejmeter-pluginsweb-api-testing

how to get pass in Jmeter reports for 404 response codes?


Scenario:

I am doing API testing using Jmeter. I have added a response code assertion there for 404 i.e. I am expecting 404.

So when I am expecting it, it should be green but it is red (it appears green for 200). How can I fix it?

I am using Jmeter 3.x on windows and listener is JMeter View Results in table


Solution

  • You can override sampler result, using JSR223 Assertion (or any other programmable assertion or post-processor):

    1. Add JSR223 Assertion under the sampler you want to pass when response code is 404:

    enter image description here

    1. Set assertion so that it passes if response code is 404, and in that case also modify sampler's result to be successful. In all other cases, set assertion to fail, and do not modify sampler status:

      if("404".equals(SampleResult.getResponseCode())) { // Success
          SampleResult.setSuccessful(true); // Change sampler status to success
          AssertionResult.setFailure(false); // Set assertion status to success as well
      } 
      else {
          AssertionResult.setFailure(true); // Set assertion status to failure
      }
      

    This code only overrides the status, you may however change any other fields of the SampleResult and AssertionResult

    Example:

    When response code is 404, sampler and assertion will succeed:

    enter image description here

    When response code is 200, sampler will initially succeed, but will fail due to assertion:

    enter image description here