'Exact matching for headers with MockServer

I use MockServer to test my application and I need the request definition to match only if the exact headers set was matched, i.e. there are no missing nor extra headers in the request.

Using this Kotlin code it matches any request that contains at least specified headers, so if the request has other headers, it matches it too:

mockServer
    .`when`(
        request()
            .withPath("/somePath")
            .withHeaders(
                Headers(
                    header("header1", "value1")
                    header("header2", "value2")
                    
                ).withKeyMatchStyle(KeyMatchStyle.MATCHING_KEY)
            )            
    )
    .respond(
        response()
            .withContentType(MediaType.APPLICATION_JSON_UTF_8)
            .withBody("OK")
    )

Is there a way to configure MockServer to fail if a request contains unspecified headers? After reading the docs, I didn't find how to do this.



Solution 1:[1]

I also tried to solve same problem and bumped into that question.

The simplest solution is just to remove .withKeyMatchStyle(KeyMatchStyle.MATCHING_KEY).

But you can also write something like that:

mockServer.when(
    request()
        .withPath("/somePath")
        .withHeader(NottableString.not("header1"), NottableString.string(".*"))
        .withHeader(NottableString.not("header2"), NottableString.string(".*"))
        .withHeaders(
            Headers(
                header("header1", "value1")
                header("header2", "value2")
                
            ).withKeyMatchStyle(KeyMatchStyle.MATCHING_KEY)
        )            
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1