The he/him test is much overrated, especially when it comes
without instructions for use in complex sentences.
Let's parse it as a statement, not an order, ok?
- He'll give the key to whoever needs to open that cabinet
is indeed correct. Whomever would be ungrammatical. That follows the actual rule.
The reason why the he/him test doesn't work here
is that the wh-ever word is
- after the preposition to (where him would work),
- before the tensed verb needs (where he would work).
So the question is whether the wh-ever word is (respectively)
- the object of the preposition to
- the subject of the verb needs.
Elimination gives the answer. It has to be one or the other.
On the one hand, if it's the object of the preposition, it can't be the subject; but then what is the subject of needs? This is a tensed clause, and they require a subject. That's a problem.
On the other hand, if it's the subject of needs, then that requirement is filled, but what's the object of to? Well, it's the whole Wh-complement clause (which is in fact a noun phrase and can be an object or a subject) whoever needs to open that cabinet. That clause describes and refers to the indefinite person who is the legitimate receiver of the key, the one who needs it. So that's no problem.
By elimination, then, it's whoever.