Like many other government jobs, hiring and promotion in the NYPD (and other major police departments) is based on civil service rules. The promotion tests are civil service exams.
Before the civil service laws, much government hiring and promotion was based on political patronage, which caused great abuses. The civil service system was instituted so that positions would be filled by the most qualified people based on objective testing, rather than pure favoritism.
In a post from 2004, I explained the NYPD rank structure, including the civil service exam promotions (to Sergeant, Lieutenant and Captain) and the promotions outside the realm of the exams.
Every single agency has different policies regarding this. So there could be a zillion answers. Policies, laws, civil service rules, and union contracts all differ but all can play a part in how promotions are done. So YMMV depending on your locale.
I didn’t have to take a test when I got promoted into the Detective Bureau, but when I previously had tried to become a patrol Sergeant I did have to take a test. Remember though, a Sheriff is an elected official and can pretty much ignore a lot of stuff. Ours promoted a non-sworn correction officer all the way up to Major, bypassing every other rank and every other person of greater qualifications.
There is still a ton of politics and cronyism in this field. A lot of agencies stick to the rules and policies, but others it’s not what you know it’s who you know, and for some it’s not who you know it’s who you blow.