Skip to content
Advertisement

PHPUnit: Verifying that array has a key with given value

Given the following class:

JavaScript

And this testcase:

JavaScript

How do I verify that $params (which is an array) and is passed to $Other->post() contains a key named ‘key1’ that has a value of ‘Value 1’?

I do not want to verify all of the array – this is just a sample code, in actual code the passed array has a lot more values, I want to verify just a single key/value pair in there.

There is $this->arrayHasKey('keyname') that I can use to verify that the key exists.

There is also $this->contains('Value 1'), which can be used to verify that the array has this value.

I could even combine those two with $this->logicalAnd. But this of course does not give the desired result.

So far I have been using returnCallback, capturing the whole $params and then doing asserts on that, but is there perhaps another way to do what I want?

Advertisement

Answer

I ended up creating my own constraint class, based on the attribute one

JavaScript

It can be used like this:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement