That's not exactly true. In the US you can generally be compelled to testify if you are not the one on trial unless you claim the 5th (the law generally recognizes that court proceedings are part of the record and testimony there could be used to bring charges against you later).
There can be a series of escalations and motions before the judge, eg where the judge asks you in closed court to give more details so he/she can rule on whether the 5th applies. In theory you could refuse to give any details by claiming even the tiniest detail would put you at risk of prosecution. Ultimately if the prosecutor offers you blanket immunity you can no longer claim the 5th because the threat of prosecution has been eliminated.
Similarly if you refuse to testify for fear of your own safety the government can offer to protect you, up to and including putting you into witness protection which eliminates the objection.
The general principle seems to be you have a series of objections you can raise. Each one imposes a higher and higher cost on the government, forcing them to decide just how important your testimony really is.
This is all separate from the material witness procedures, which have been abused somewhat in recent times. The theory there is there is an imminent thread to your life _or_ you are a serious flight risk. In those cases you get jailed until trial despite not even being accused. As you can imagine prosecutors have sometimes used the threat of losing your job, house, etc while jailed awaiting trial to coerce testimony.