In real life, if an undercover police officer is asked whether he or she is a cop, do they have to tell the truth? The short answer is no.
Police officers are allowed to lie to suspected criminals. The police officer who lies and says he is not a cop will not get in trouble, and any evidence he collects as part of the undercover operation can be used in court.
I have sometimes been asked, isn't it entrapment when a police officer lies and says he is not a cop? Again, the answer is no.
Entrapment generally occurs when a police officer (or other government agent) induces the defendant to commit a crime he would not have otherwise committed. Simply providing someone the opportunity to commit a crime is not entrapment. Certainly telling someone that he or she is not a cop would not induce someone to commit a crime they would not have otherwise committed.
So, why do television shows and movies always do this? I don't have a good answer for that. Maybe it's an easy way to show the criminal is suspicious of the undercover cop. Maybe it's laziness or ignorance on the part of the writers. One thing is for sure: it is overused and suggests an incorrect legal standard.
For more information like this, check out a free ebook revealing the Top 7 Mistakes Made by Writer of Crime, Mystery, and Legal Drama.